PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 11ms app.codeStats 1ms

/php/PHP_CodeSniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php

http://github.com/jonswar/perl-code-tidyall
PHP | 879 lines | 639 code | 120 blank | 120 comment | 171 complexity | f0e5a28bcd5e0abdd15913769a8eb604 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, 0BSD, MIT
  1. <?php
  2. /**
  3. * Ensures that arrays conform to the array coding standard.
  4. *
  5. * @author Greg Sherwood <gsherwood@squiz.net>
  6. * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
  7. * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
  8. */
  9. namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays;
  10. use PHP_CodeSniffer\Sniffs\Sniff;
  11. use PHP_CodeSniffer\Files\File;
  12. use PHP_CodeSniffer\Util\Tokens;
  13. class ArrayDeclarationSniff implements Sniff
  14. {
  15. /**
  16. * Returns an array of tokens this test wants to listen for.
  17. *
  18. * @return array
  19. */
  20. public function register()
  21. {
  22. return [
  23. T_ARRAY,
  24. T_OPEN_SHORT_ARRAY,
  25. ];
  26. }//end register()
  27. /**
  28. * Processes this sniff, when one of its tokens is encountered.
  29. *
  30. * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked.
  31. * @param int $stackPtr The position of the current token in
  32. * the stack passed in $tokens.
  33. *
  34. * @return void
  35. */
  36. public function process(File $phpcsFile, $stackPtr)
  37. {
  38. $tokens = $phpcsFile->getTokens();
  39. if ($tokens[$stackPtr]['code'] === T_ARRAY) {
  40. $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'no');
  41. // Array keyword should be lower case.
  42. if ($tokens[$stackPtr]['content'] !== strtolower($tokens[$stackPtr]['content'])) {
  43. if ($tokens[$stackPtr]['content'] === strtoupper($tokens[$stackPtr]['content'])) {
  44. $phpcsFile->recordMetric($stackPtr, 'Array keyword case', 'upper');
  45. } else {
  46. $phpcsFile->recordMetric($stackPtr, 'Array keyword case', 'mixed');
  47. }
  48. $error = 'Array keyword should be lower case; expected "array" but found "%s"';
  49. $data = [$tokens[$stackPtr]['content']];
  50. $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotLowerCase', $data);
  51. if ($fix === true) {
  52. $phpcsFile->fixer->replaceToken($stackPtr, 'array');
  53. }
  54. } else {
  55. $phpcsFile->recordMetric($stackPtr, 'Array keyword case', 'lower');
  56. }
  57. $arrayStart = $tokens[$stackPtr]['parenthesis_opener'];
  58. if (isset($tokens[$arrayStart]['parenthesis_closer']) === false) {
  59. return;
  60. }
  61. $arrayEnd = $tokens[$arrayStart]['parenthesis_closer'];
  62. if ($arrayStart !== ($stackPtr + 1)) {
  63. $error = 'There must be no space between the "array" keyword and the opening parenthesis';
  64. $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $arrayStart, true);
  65. if (isset(Tokens::$commentTokens[$tokens[$next]['code']]) === true) {
  66. // We don't have anywhere to put the comment, so don't attempt to fix it.
  67. $phpcsFile->addError($error, $stackPtr, 'SpaceAfterKeyword');
  68. } else {
  69. $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterKeyword');
  70. if ($fix === true) {
  71. $phpcsFile->fixer->beginChangeset();
  72. for ($i = ($stackPtr + 1); $i < $arrayStart; $i++) {
  73. $phpcsFile->fixer->replaceToken($i, '');
  74. }
  75. $phpcsFile->fixer->endChangeset();
  76. }
  77. }
  78. }
  79. } else {
  80. $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes');
  81. $arrayStart = $stackPtr;
  82. $arrayEnd = $tokens[$stackPtr]['bracket_closer'];
  83. }//end if
  84. // Check for empty arrays.
  85. $content = $phpcsFile->findNext(T_WHITESPACE, ($arrayStart + 1), ($arrayEnd + 1), true);
  86. if ($content === $arrayEnd) {
  87. // Empty array, but if the brackets aren't together, there's a problem.
  88. if (($arrayEnd - $arrayStart) !== 1) {
  89. $error = 'Empty array declaration must have no space between the parentheses';
  90. $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceInEmptyArray');
  91. if ($fix === true) {
  92. $phpcsFile->fixer->beginChangeset();
  93. for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) {
  94. $phpcsFile->fixer->replaceToken($i, '');
  95. }
  96. $phpcsFile->fixer->endChangeset();
  97. }
  98. }
  99. // We can return here because there is nothing else to check. All code
  100. // below can assume that the array is not empty.
  101. return;
  102. }
  103. if ($tokens[$arrayStart]['line'] === $tokens[$arrayEnd]['line']) {
  104. $this->processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd);
  105. } else {
  106. $this->processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd);
  107. }
  108. }//end process()
  109. /**
  110. * Processes a single-line array definition.
  111. *
  112. * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked.
  113. * @param int $stackPtr The position of the current token
  114. * in the stack passed in $tokens.
  115. * @param int $arrayStart The token that starts the array definition.
  116. * @param int $arrayEnd The token that ends the array definition.
  117. *
  118. * @return void
  119. */
  120. public function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd)
  121. {
  122. $tokens = $phpcsFile->getTokens();
  123. // Check if there are multiple values. If so, then it has to be multiple lines
  124. // unless it is contained inside a function call or condition.
  125. $valueCount = 0;
  126. $commas = [];
  127. for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) {
  128. // Skip bracketed statements, like function calls.
  129. if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) {
  130. $i = $tokens[$i]['parenthesis_closer'];
  131. continue;
  132. }
  133. if ($tokens[$i]['code'] === T_COMMA) {
  134. // Before counting this comma, make sure we are not
  135. // at the end of the array.
  136. $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), $arrayEnd, true);
  137. if ($next !== false) {
  138. $valueCount++;
  139. $commas[] = $i;
  140. } else {
  141. // There is a comma at the end of a single line array.
  142. $error = 'Comma not allowed after last value in single-line array declaration';
  143. $fix = $phpcsFile->addFixableError($error, $i, 'CommaAfterLast');
  144. if ($fix === true) {
  145. $phpcsFile->fixer->replaceToken($i, '');
  146. }
  147. }
  148. }
  149. }//end for
  150. // Now check each of the double arrows (if any).
  151. $nextArrow = $arrayStart;
  152. while (($nextArrow = $phpcsFile->findNext(T_DOUBLE_ARROW, ($nextArrow + 1), $arrayEnd)) !== false) {
  153. if ($tokens[($nextArrow - 1)]['code'] !== T_WHITESPACE) {
  154. $content = $tokens[($nextArrow - 1)]['content'];
  155. $error = 'Expected 1 space between "%s" and double arrow; 0 found';
  156. $data = [$content];
  157. $fix = $phpcsFile->addFixableError($error, $nextArrow, 'NoSpaceBeforeDoubleArrow', $data);
  158. if ($fix === true) {
  159. $phpcsFile->fixer->addContentBefore($nextArrow, ' ');
  160. }
  161. } else {
  162. $spaceLength = $tokens[($nextArrow - 1)]['length'];
  163. if ($spaceLength !== 1) {
  164. $content = $tokens[($nextArrow - 2)]['content'];
  165. $error = 'Expected 1 space between "%s" and double arrow; %s found';
  166. $data = [
  167. $content,
  168. $spaceLength,
  169. ];
  170. $fix = $phpcsFile->addFixableError($error, $nextArrow, 'SpaceBeforeDoubleArrow', $data);
  171. if ($fix === true) {
  172. $phpcsFile->fixer->replaceToken(($nextArrow - 1), ' ');
  173. }
  174. }
  175. }//end if
  176. if ($tokens[($nextArrow + 1)]['code'] !== T_WHITESPACE) {
  177. $content = $tokens[($nextArrow + 1)]['content'];
  178. $error = 'Expected 1 space between double arrow and "%s"; 0 found';
  179. $data = [$content];
  180. $fix = $phpcsFile->addFixableError($error, $nextArrow, 'NoSpaceAfterDoubleArrow', $data);
  181. if ($fix === true) {
  182. $phpcsFile->fixer->addContent($nextArrow, ' ');
  183. }
  184. } else {
  185. $spaceLength = $tokens[($nextArrow + 1)]['length'];
  186. if ($spaceLength !== 1) {
  187. $content = $tokens[($nextArrow + 2)]['content'];
  188. $error = 'Expected 1 space between double arrow and "%s"; %s found';
  189. $data = [
  190. $content,
  191. $spaceLength,
  192. ];
  193. $fix = $phpcsFile->addFixableError($error, $nextArrow, 'SpaceAfterDoubleArrow', $data);
  194. if ($fix === true) {
  195. $phpcsFile->fixer->replaceToken(($nextArrow + 1), ' ');
  196. }
  197. }
  198. }//end if
  199. }//end while
  200. if ($valueCount > 0) {
  201. $nestedParenthesis = false;
  202. if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
  203. $nested = $tokens[$stackPtr]['nested_parenthesis'];
  204. $nestedParenthesis = array_pop($nested);
  205. }
  206. if ($nestedParenthesis === false
  207. || $tokens[$nestedParenthesis]['line'] !== $tokens[$stackPtr]['line']
  208. ) {
  209. $error = 'Array with multiple values cannot be declared on a single line';
  210. $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SingleLineNotAllowed');
  211. if ($fix === true) {
  212. $phpcsFile->fixer->beginChangeset();
  213. $phpcsFile->fixer->addNewline($arrayStart);
  214. $phpcsFile->fixer->addNewlineBefore($arrayEnd);
  215. $phpcsFile->fixer->endChangeset();
  216. }
  217. return;
  218. }
  219. // We have a multiple value array that is inside a condition or
  220. // function. Check its spacing is correct.
  221. foreach ($commas as $comma) {
  222. if ($tokens[($comma + 1)]['code'] !== T_WHITESPACE) {
  223. $content = $tokens[($comma + 1)]['content'];
  224. $error = 'Expected 1 space between comma and "%s"; 0 found';
  225. $data = [$content];
  226. $fix = $phpcsFile->addFixableError($error, $comma, 'NoSpaceAfterComma', $data);
  227. if ($fix === true) {
  228. $phpcsFile->fixer->addContent($comma, ' ');
  229. }
  230. } else {
  231. $spaceLength = $tokens[($comma + 1)]['length'];
  232. if ($spaceLength !== 1) {
  233. $content = $tokens[($comma + 2)]['content'];
  234. $error = 'Expected 1 space between comma and "%s"; %s found';
  235. $data = [
  236. $content,
  237. $spaceLength,
  238. ];
  239. $fix = $phpcsFile->addFixableError($error, $comma, 'SpaceAfterComma', $data);
  240. if ($fix === true) {
  241. $phpcsFile->fixer->replaceToken(($comma + 1), ' ');
  242. }
  243. }
  244. }//end if
  245. if ($tokens[($comma - 1)]['code'] === T_WHITESPACE) {
  246. $content = $tokens[($comma - 2)]['content'];
  247. $spaceLength = $tokens[($comma - 1)]['length'];
  248. $error = 'Expected 0 spaces between "%s" and comma; %s found';
  249. $data = [
  250. $content,
  251. $spaceLength,
  252. ];
  253. $fix = $phpcsFile->addFixableError($error, $comma, 'SpaceBeforeComma', $data);
  254. if ($fix === true) {
  255. $phpcsFile->fixer->replaceToken(($comma - 1), '');
  256. }
  257. }
  258. }//end foreach
  259. }//end if
  260. }//end processSingleLineArray()
  261. /**
  262. * Processes a multi-line array definition.
  263. *
  264. * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked.
  265. * @param int $stackPtr The position of the current token
  266. * in the stack passed in $tokens.
  267. * @param int $arrayStart The token that starts the array definition.
  268. * @param int $arrayEnd The token that ends the array definition.
  269. *
  270. * @return void
  271. */
  272. public function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd)
  273. {
  274. $tokens = $phpcsFile->getTokens();
  275. $keywordStart = $tokens[$stackPtr]['column'];
  276. // Check the closing bracket is on a new line.
  277. $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($arrayEnd - 1), $arrayStart, true);
  278. if ($tokens[$lastContent]['line'] === $tokens[$arrayEnd]['line']) {
  279. $error = 'Closing parenthesis of array declaration must be on a new line';
  280. $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNewLine');
  281. if ($fix === true) {
  282. $phpcsFile->fixer->addNewlineBefore($arrayEnd);
  283. }
  284. } else if ($tokens[$arrayEnd]['column'] !== $keywordStart) {
  285. // Check the closing bracket is lined up under the "a" in array.
  286. $expected = ($keywordStart - 1);
  287. $found = ($tokens[$arrayEnd]['column'] - 1);
  288. $error = 'Closing parenthesis not aligned correctly; expected %s space(s) but found %s';
  289. $data = [
  290. $expected,
  291. $found,
  292. ];
  293. $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNotAligned', $data);
  294. if ($fix === true) {
  295. if ($found === 0) {
  296. $phpcsFile->fixer->addContent(($arrayEnd - 1), str_repeat(' ', $expected));
  297. } else {
  298. $phpcsFile->fixer->replaceToken(($arrayEnd - 1), str_repeat(' ', $expected));
  299. }
  300. }
  301. }//end if
  302. $keyUsed = false;
  303. $singleUsed = false;
  304. $indices = [];
  305. $maxLength = 0;
  306. if ($tokens[$stackPtr]['code'] === T_ARRAY) {
  307. $lastToken = $tokens[$stackPtr]['parenthesis_opener'];
  308. } else {
  309. $lastToken = $stackPtr;
  310. }
  311. // Find all the double arrows that reside in this scope.
  312. for ($nextToken = ($stackPtr + 1); $nextToken < $arrayEnd; $nextToken++) {
  313. // Skip bracketed statements, like function calls.
  314. if ($tokens[$nextToken]['code'] === T_OPEN_PARENTHESIS
  315. && (isset($tokens[$nextToken]['parenthesis_owner']) === false
  316. || $tokens[$nextToken]['parenthesis_owner'] !== $stackPtr)
  317. ) {
  318. $nextToken = $tokens[$nextToken]['parenthesis_closer'];
  319. continue;
  320. }
  321. if ($tokens[$nextToken]['code'] === T_ARRAY
  322. || $tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY
  323. || $tokens[$nextToken]['code'] === T_CLOSURE
  324. ) {
  325. // Let subsequent calls of this test handle nested arrays.
  326. if ($tokens[$lastToken]['code'] !== T_DOUBLE_ARROW) {
  327. $indices[] = ['value' => $nextToken];
  328. $lastToken = $nextToken;
  329. }
  330. if ($tokens[$nextToken]['code'] === T_ARRAY) {
  331. $nextToken = $tokens[$tokens[$nextToken]['parenthesis_opener']]['parenthesis_closer'];
  332. } else if ($tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY) {
  333. $nextToken = $tokens[$nextToken]['bracket_closer'];
  334. } else {
  335. // T_CLOSURE.
  336. $nextToken = $tokens[$nextToken]['scope_closer'];
  337. }
  338. $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true);
  339. if ($tokens[$nextToken]['code'] !== T_COMMA) {
  340. $nextToken--;
  341. } else {
  342. $lastToken = $nextToken;
  343. }
  344. continue;
  345. }//end if
  346. if ($tokens[$nextToken]['code'] !== T_DOUBLE_ARROW
  347. && $tokens[$nextToken]['code'] !== T_COMMA
  348. ) {
  349. continue;
  350. }
  351. $currentEntry = [];
  352. if ($tokens[$nextToken]['code'] === T_COMMA) {
  353. $stackPtrCount = 0;
  354. if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) {
  355. $stackPtrCount = count($tokens[$stackPtr]['nested_parenthesis']);
  356. }
  357. $commaCount = 0;
  358. if (isset($tokens[$nextToken]['nested_parenthesis']) === true) {
  359. $commaCount = count($tokens[$nextToken]['nested_parenthesis']);
  360. if ($tokens[$stackPtr]['code'] === T_ARRAY) {
  361. // Remove parenthesis that are used to define the array.
  362. $commaCount--;
  363. }
  364. }
  365. if ($commaCount > $stackPtrCount) {
  366. // This comma is inside more parenthesis than the ARRAY keyword,
  367. // then there it is actually a comma used to separate arguments
  368. // in a function call.
  369. continue;
  370. }
  371. if ($keyUsed === true && $tokens[$lastToken]['code'] === T_COMMA) {
  372. $error = 'No key specified for array entry; first entry specifies key';
  373. $phpcsFile->addError($error, $nextToken, 'NoKeySpecified');
  374. return;
  375. }
  376. if ($keyUsed === false) {
  377. if ($tokens[($nextToken - 1)]['code'] === T_WHITESPACE) {
  378. $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($nextToken - 1), null, true);
  379. if (($tokens[$prev]['code'] !== T_END_HEREDOC
  380. && $tokens[$prev]['code'] !== T_END_NOWDOC)
  381. || $tokens[($nextToken - 1)]['line'] === $tokens[$nextToken]['line']
  382. ) {
  383. $content = $tokens[($nextToken - 2)]['content'];
  384. if ($tokens[($nextToken - 1)]['content'] === $phpcsFile->eolChar) {
  385. $spaceLength = 'newline';
  386. } else {
  387. $spaceLength = $tokens[($nextToken - 1)]['length'];
  388. }
  389. $error = 'Expected 0 spaces before comma; %s found';
  390. $data = [$spaceLength];
  391. $fix = $phpcsFile->addFixableError($error, $nextToken, 'SpaceBeforeComma', $data);
  392. if ($fix === true) {
  393. $phpcsFile->fixer->replaceToken(($nextToken - 1), '');
  394. }
  395. }
  396. }//end if
  397. $valueContent = $phpcsFile->findNext(
  398. Tokens::$emptyTokens,
  399. ($lastToken + 1),
  400. $nextToken,
  401. true
  402. );
  403. $indices[] = ['value' => $valueContent];
  404. $singleUsed = true;
  405. }//end if
  406. $lastToken = $nextToken;
  407. continue;
  408. }//end if
  409. if ($tokens[$nextToken]['code'] === T_DOUBLE_ARROW) {
  410. if ($singleUsed === true) {
  411. $error = 'Key specified for array entry; first entry has no key';
  412. $phpcsFile->addError($error, $nextToken, 'KeySpecified');
  413. return;
  414. }
  415. $currentEntry['arrow'] = $nextToken;
  416. $keyUsed = true;
  417. // Find the start of index that uses this double arrow.
  418. $indexEnd = $phpcsFile->findPrevious(T_WHITESPACE, ($nextToken - 1), $arrayStart, true);
  419. $indexStart = $phpcsFile->findStartOfStatement($indexEnd);
  420. if ($indexStart === $indexEnd) {
  421. $currentEntry['index'] = $indexEnd;
  422. $currentEntry['index_content'] = $tokens[$indexEnd]['content'];
  423. $currentEntry['index_length'] = $tokens[$indexEnd]['length'];
  424. } else {
  425. $currentEntry['index'] = $indexStart;
  426. $currentEntry['index_content'] = '';
  427. $currentEntry['index_length'] = 0;
  428. for ($i = $indexStart; $i <= $indexEnd; $i++) {
  429. $currentEntry['index_content'] .= $tokens[$i]['content'];
  430. $currentEntry['index_length'] += $tokens[$i]['length'];
  431. }
  432. }
  433. if ($maxLength < $currentEntry['index_length']) {
  434. $maxLength = $currentEntry['index_length'];
  435. }
  436. // Find the value of this index.
  437. $nextContent = $phpcsFile->findNext(
  438. Tokens::$emptyTokens,
  439. ($nextToken + 1),
  440. $arrayEnd,
  441. true
  442. );
  443. $currentEntry['value'] = $nextContent;
  444. $indices[] = $currentEntry;
  445. $lastToken = $nextToken;
  446. }//end if
  447. }//end for
  448. // Check for multi-line arrays that should be single-line.
  449. $singleValue = false;
  450. if (empty($indices) === true) {
  451. $singleValue = true;
  452. } else if (count($indices) === 1 && $tokens[$lastToken]['code'] === T_COMMA) {
  453. // There may be another array value without a comma.
  454. $exclude = Tokens::$emptyTokens;
  455. $exclude[] = T_COMMA;
  456. $nextContent = $phpcsFile->findNext($exclude, ($indices[0]['value'] + 1), $arrayEnd, true);
  457. if ($nextContent === false) {
  458. $singleValue = true;
  459. }
  460. }
  461. if ($singleValue === true) {
  462. // Before we complain, make sure the single value isn't a here/nowdoc.
  463. $next = $phpcsFile->findNext(Tokens::$heredocTokens, ($arrayStart + 1), ($arrayEnd - 1));
  464. if ($next === false) {
  465. // Array cannot be empty, so this is a multi-line array with
  466. // a single value. It should be defined on single line.
  467. $error = 'Multi-line array contains a single value; use single-line array instead';
  468. $errorCode = 'MultiLineNotAllowed';
  469. $find = Tokens::$phpcsCommentTokens;
  470. $find[] = T_COMMENT;
  471. $comment = $phpcsFile->findNext($find, ($arrayStart + 1), $arrayEnd);
  472. if ($comment === false) {
  473. $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode);
  474. } else {
  475. $fix = false;
  476. $phpcsFile->addError($error, $stackPtr, $errorCode);
  477. }
  478. if ($fix === true) {
  479. $phpcsFile->fixer->beginChangeset();
  480. for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) {
  481. if ($tokens[$i]['code'] !== T_WHITESPACE) {
  482. break;
  483. }
  484. $phpcsFile->fixer->replaceToken($i, '');
  485. }
  486. for ($i = ($arrayEnd - 1); $i > $arrayStart; $i--) {
  487. if ($tokens[$i]['code'] !== T_WHITESPACE) {
  488. break;
  489. }
  490. $phpcsFile->fixer->replaceToken($i, '');
  491. }
  492. $phpcsFile->fixer->endChangeset();
  493. }
  494. return;
  495. }//end if
  496. }//end if
  497. /*
  498. This section checks for arrays that don't specify keys.
  499. Arrays such as:
  500. array(
  501. 'aaa',
  502. 'bbb',
  503. 'd',
  504. );
  505. */
  506. if ($keyUsed === false && empty($indices) === false) {
  507. $count = count($indices);
  508. $lastIndex = $indices[($count - 1)]['value'];
  509. $trailingContent = $phpcsFile->findPrevious(
  510. Tokens::$emptyTokens,
  511. ($arrayEnd - 1),
  512. $lastIndex,
  513. true
  514. );
  515. if ($tokens[$trailingContent]['code'] !== T_COMMA) {
  516. $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'no');
  517. $error = 'Comma required after last value in array declaration';
  518. $fix = $phpcsFile->addFixableError($error, $trailingContent, 'NoCommaAfterLast');
  519. if ($fix === true) {
  520. $phpcsFile->fixer->addContent($trailingContent, ',');
  521. }
  522. } else {
  523. $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'yes');
  524. }
  525. $lastValueLine = false;
  526. foreach ($indices as $value) {
  527. if (empty($value['value']) === true) {
  528. // Array was malformed and we couldn't figure out
  529. // the array value correctly, so we have to ignore it.
  530. // Other parts of this sniff will correct the error.
  531. continue;
  532. }
  533. if ($lastValueLine !== false && $tokens[$value['value']]['line'] === $lastValueLine) {
  534. $error = 'Each value in a multi-line array must be on a new line';
  535. $fix = $phpcsFile->addFixableError($error, $value['value'], 'ValueNoNewline');
  536. if ($fix === true) {
  537. if ($tokens[($value['value'] - 1)]['code'] === T_WHITESPACE) {
  538. $phpcsFile->fixer->replaceToken(($value['value'] - 1), '');
  539. }
  540. $phpcsFile->fixer->addNewlineBefore($value['value']);
  541. }
  542. } else if ($tokens[($value['value'] - 1)]['code'] === T_WHITESPACE) {
  543. $expected = $keywordStart;
  544. $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $value['value'], true);
  545. $found = ($tokens[$first]['column'] - 1);
  546. if ($found !== $expected) {
  547. $error = 'Array value not aligned correctly; expected %s spaces but found %s';
  548. $data = [
  549. $expected,
  550. $found,
  551. ];
  552. $fix = $phpcsFile->addFixableError($error, $value['value'], 'ValueNotAligned', $data);
  553. if ($fix === true) {
  554. if ($found === 0) {
  555. $phpcsFile->fixer->addContent(($value['value'] - 1), str_repeat(' ', $expected));
  556. } else {
  557. $phpcsFile->fixer->replaceToken(($value['value'] - 1), str_repeat(' ', $expected));
  558. }
  559. }
  560. }
  561. }//end if
  562. $lastValueLine = $tokens[$value['value']]['line'];
  563. }//end foreach
  564. }//end if
  565. /*
  566. Below the actual indentation of the array is checked.
  567. Errors will be thrown when a key is not aligned, when
  568. a double arrow is not aligned, and when a value is not
  569. aligned correctly.
  570. If an error is found in one of the above areas, then errors
  571. are not reported for the rest of the line to avoid reporting
  572. spaces and columns incorrectly. Often fixing the first
  573. problem will fix the other 2 anyway.
  574. For example:
  575. $a = array(
  576. 'index' => '2',
  577. );
  578. or
  579. $a = [
  580. 'index' => '2',
  581. ];
  582. In this array, the double arrow is indented too far, but this
  583. will also cause an error in the value's alignment. If the arrow were
  584. to be moved back one space however, then both errors would be fixed.
  585. */
  586. $numValues = count($indices);
  587. $indicesStart = ($keywordStart + 1);
  588. $indexLine = $tokens[$stackPtr]['line'];
  589. $lastIndexLine = null;
  590. foreach ($indices as $index) {
  591. if ($index['value'] === false) {
  592. // Syntax error or live coding.
  593. continue;
  594. }
  595. if (isset($index['index']) === false) {
  596. // Array value only.
  597. if ($tokens[$index['value']]['line'] === $tokens[$stackPtr]['line'] && $numValues > 1) {
  598. $error = 'The first value in a multi-value array must be on a new line';
  599. $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FirstValueNoNewline');
  600. if ($fix === true) {
  601. $phpcsFile->fixer->addNewlineBefore($index['value']);
  602. }
  603. }
  604. continue;
  605. }
  606. $lastIndexLine = $indexLine;
  607. $indexLine = $tokens[$index['index']]['line'];
  608. if ($indexLine === $tokens[$stackPtr]['line']) {
  609. $error = 'The first index in a multi-value array must be on a new line';
  610. $fix = $phpcsFile->addFixableError($error, $index['index'], 'FirstIndexNoNewline');
  611. if ($fix === true) {
  612. $phpcsFile->fixer->addNewlineBefore($index['index']);
  613. }
  614. continue;
  615. }
  616. if ($indexLine === $lastIndexLine) {
  617. $error = 'Each index in a multi-line array must be on a new line';
  618. $fix = $phpcsFile->addFixableError($error, $index['index'], 'IndexNoNewline');
  619. if ($fix === true) {
  620. if ($tokens[($index['index'] - 1)]['code'] === T_WHITESPACE) {
  621. $phpcsFile->fixer->replaceToken(($index['index'] - 1), '');
  622. }
  623. $phpcsFile->fixer->addNewlineBefore($index['index']);
  624. }
  625. continue;
  626. }
  627. if ($tokens[$index['index']]['column'] !== $indicesStart
  628. && ($index['index'] - 1) !== $arrayStart
  629. ) {
  630. $expected = ($indicesStart - 1);
  631. $found = ($tokens[$index['index']]['column'] - 1);
  632. $error = 'Array key not aligned correctly; expected %s spaces but found %s';
  633. $data = [
  634. $expected,
  635. $found,
  636. ];
  637. $fix = $phpcsFile->addFixableError($error, $index['index'], 'KeyNotAligned', $data);
  638. if ($fix === true) {
  639. if ($found === 0 || $tokens[($index['index'] - 1)]['code'] !== T_WHITESPACE) {
  640. $phpcsFile->fixer->addContent(($index['index'] - 1), str_repeat(' ', $expected));
  641. } else {
  642. $phpcsFile->fixer->replaceToken(($index['index'] - 1), str_repeat(' ', $expected));
  643. }
  644. }
  645. }
  646. $arrowStart = ($tokens[$index['index']]['column'] + $maxLength + 1);
  647. if ($tokens[$index['arrow']]['column'] !== $arrowStart) {
  648. $expected = ($arrowStart - ($index['index_length'] + $tokens[$index['index']]['column']));
  649. $found = ($tokens[$index['arrow']]['column'] - ($index['index_length'] + $tokens[$index['index']]['column']));
  650. $error = 'Array double arrow not aligned correctly; expected %s space(s) but found %s';
  651. $data = [
  652. $expected,
  653. $found,
  654. ];
  655. $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'DoubleArrowNotAligned', $data);
  656. if ($fix === true) {
  657. if ($found === 0) {
  658. $phpcsFile->fixer->addContent(($index['arrow'] - 1), str_repeat(' ', $expected));
  659. } else {
  660. $phpcsFile->fixer->replaceToken(($index['arrow'] - 1), str_repeat(' ', $expected));
  661. }
  662. }
  663. continue;
  664. }
  665. $valueStart = ($arrowStart + 3);
  666. if ($tokens[$index['value']]['column'] !== $valueStart) {
  667. $expected = ($valueStart - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column']));
  668. $found = ($tokens[$index['value']]['column'] - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column']));
  669. if ($found < 0) {
  670. $found = 'newline';
  671. }
  672. $error = 'Array value not aligned correctly; expected %s space(s) but found %s';
  673. $data = [
  674. $expected,
  675. $found,
  676. ];
  677. $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'ValueNotAligned', $data);
  678. if ($fix === true) {
  679. if ($found === 'newline') {
  680. $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($index['value'] - 1), null, true);
  681. $phpcsFile->fixer->beginChangeset();
  682. for ($i = ($prev + 1); $i < $index['value']; $i++) {
  683. $phpcsFile->fixer->replaceToken($i, '');
  684. }
  685. $phpcsFile->fixer->replaceToken(($index['value'] - 1), str_repeat(' ', $expected));
  686. $phpcsFile->fixer->endChangeset();
  687. } else if ($found === 0) {
  688. $phpcsFile->fixer->addContent(($index['value'] - 1), str_repeat(' ', $expected));
  689. } else {
  690. $phpcsFile->fixer->replaceToken(($index['value'] - 1), str_repeat(' ', $expected));
  691. }
  692. }
  693. }//end if
  694. // Check each line ends in a comma.
  695. $valueStart = $index['value'];
  696. $valueLine = $tokens[$index['value']]['line'];
  697. $nextComma = false;
  698. $end = $phpcsFile->findEndOfStatement($valueStart);
  699. if ($end === false) {
  700. $valueEnd = $valueStart;
  701. } else if ($tokens[$end]['code'] === T_COMMA) {
  702. $valueEnd = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($end - 1), $valueStart, true);
  703. $nextComma = $end;
  704. } else {
  705. $valueEnd = $end;
  706. $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $arrayEnd, true);
  707. if ($next !== false && $tokens[$next]['code'] === T_COMMA) {
  708. $nextComma = $next;
  709. }
  710. }
  711. $valueLine = $tokens[$valueEnd]['line'];
  712. if ($tokens[$valueEnd]['code'] === T_END_HEREDOC || $tokens[$valueEnd]['code'] === T_END_NOWDOC) {
  713. $valueLine++;
  714. }
  715. if ($nextComma === false || ($tokens[$nextComma]['line'] !== $valueLine)) {
  716. $error = 'Each line in an array declaration must end in a comma';
  717. $fix = $phpcsFile->addFixableError($error, $index['value'], 'NoComma');
  718. if ($fix === true) {
  719. // Find the end of the line and put a comma there.
  720. for ($i = ($index['value'] + 1); $i <= $arrayEnd; $i++) {
  721. if ($tokens[$i]['line'] > $valueLine) {
  722. break;
  723. }
  724. }
  725. $phpcsFile->fixer->beginChangeset();
  726. $phpcsFile->fixer->addContentBefore(($i - 1), ',');
  727. if ($nextComma !== false) {
  728. $phpcsFile->fixer->replaceToken($nextComma, '');
  729. }
  730. $phpcsFile->fixer->endChangeset();
  731. }
  732. }//end if
  733. // Check that there is no space before the comma.
  734. if ($nextComma !== false && $tokens[($nextComma - 1)]['code'] === T_WHITESPACE) {
  735. // Here/nowdoc closing tags must have the comma on the next line.
  736. $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($nextComma - 1), null, true);
  737. if ($tokens[$prev]['code'] !== T_END_HEREDOC && $tokens[$prev]['code'] !== T_END_NOWDOC) {
  738. $content = $tokens[($nextComma - 2)]['content'];
  739. $spaceLength = $tokens[($nextComma - 1)]['length'];
  740. $error = 'Expected 0 spaces between "%s" and comma; %s found';
  741. $data = [
  742. $content,
  743. $spaceLength,
  744. ];
  745. $fix = $phpcsFile->addFixableError($error, $nextComma, 'SpaceBeforeComma', $data);
  746. if ($fix === true) {
  747. $phpcsFile->fixer->replaceToken(($nextComma - 1), '');
  748. }
  749. }
  750. }
  751. }//end foreach
  752. }//end processMultiLineArray()
  753. }//end class