MethodArgumentsSniff.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Sniffs\Annotation;
  8. use PHP_CodeSniffer\Sniffs\Sniff;
  9. use PHP_CodeSniffer\Files\File;
  10. /**
  11. * Sniff to validate method arguments annotations
  12. */
  13. class MethodArgumentsSniff implements Sniff
  14. {
  15. /**
  16. * @var array
  17. */
  18. private $validTokensBeforeClosingCommentTag = [
  19. 'T_WHITESPACE',
  20. 'T_PUBLIC',
  21. 'T_PRIVATE',
  22. 'T_PROTECTED',
  23. 'T_STATIC',
  24. 'T_ABSTRACT',
  25. 'T_FINAL'
  26. ];
  27. /**
  28. * @var array
  29. */
  30. private $invalidTypes = [
  31. 'null',
  32. 'false',
  33. 'true',
  34. 'self'
  35. ];
  36. /**
  37. * @inheritdoc
  38. */
  39. public function register() : array
  40. {
  41. return [
  42. T_FUNCTION
  43. ];
  44. }
  45. /**
  46. * Validates whether valid token exists before closing comment tag
  47. *
  48. * @param string $type
  49. * @return bool
  50. */
  51. private function isTokenBeforeClosingCommentTagValid(string $type) : bool
  52. {
  53. return in_array($type, $this->validTokensBeforeClosingCommentTag);
  54. }
  55. /**
  56. * Validates whether comment block exists
  57. *
  58. * @param File $phpcsFile
  59. * @param int $previousCommentClosePtr
  60. * @param int $stackPtr
  61. * @return bool
  62. */
  63. private function validateCommentBlockExists(File $phpcsFile, int $previousCommentClosePtr, int $stackPtr) : bool
  64. {
  65. $tokens = $phpcsFile->getTokens();
  66. for ($tempPtr = $previousCommentClosePtr + 1; $tempPtr < $stackPtr; $tempPtr++) {
  67. if (!$this->isTokenBeforeClosingCommentTagValid($tokens[$tempPtr]['type'])) {
  68. return false;
  69. }
  70. }
  71. return true;
  72. }
  73. /**
  74. * Checks whether the parameter type is invalid
  75. *
  76. * @param string $type
  77. * @return bool
  78. */
  79. private function isInvalidType(string $type) : bool
  80. {
  81. return in_array(strtolower($type), $this->invalidTypes);
  82. }
  83. /**
  84. * Get arguments from method signature
  85. *
  86. * @param File $phpcsFile
  87. * @param int $openParenthesisPtr
  88. * @param int $closedParenthesisPtr
  89. * @return array
  90. */
  91. private function getMethodArguments(File $phpcsFile, int $openParenthesisPtr, int $closedParenthesisPtr) : array
  92. {
  93. $tokens = $phpcsFile->getTokens();
  94. $methodArguments = [];
  95. for ($i = $openParenthesisPtr; $i < $closedParenthesisPtr; $i++) {
  96. $argumentsPtr = $phpcsFile->findNext(T_VARIABLE, $i + 1, $closedParenthesisPtr);
  97. if ($argumentsPtr === false) {
  98. break;
  99. } elseif ($argumentsPtr < $closedParenthesisPtr) {
  100. $arguments = $tokens[$argumentsPtr]['content'];
  101. $methodArguments[] = $arguments;
  102. $i = $argumentsPtr - 1;
  103. }
  104. }
  105. return $methodArguments;
  106. }
  107. /**
  108. * Get parameters from method annotation
  109. *
  110. * @param array $paramDefinitions
  111. * @return array
  112. */
  113. private function getMethodParameters(array $paramDefinitions) : array
  114. {
  115. $paramName = [];
  116. for ($i = 0; $i < count($paramDefinitions); $i++) {
  117. if (isset($paramDefinitions[$i]['paramName'])) {
  118. $paramName[] = $paramDefinitions[$i]['paramName'];
  119. }
  120. }
  121. return $paramName;
  122. }
  123. /**
  124. * Validates whether @inheritdoc without braces [@inheritdoc] exists or not
  125. *
  126. * @param File $phpcsFile
  127. * @param int $previousCommentOpenPtr
  128. * @param int $previousCommentClosePtr
  129. */
  130. private function validateInheritdocAnnotationWithoutBracesExists(
  131. File $phpcsFile,
  132. int $previousCommentOpenPtr,
  133. int $previousCommentClosePtr
  134. ) : bool {
  135. return $this->validateInheritdocAnnotationExists(
  136. $phpcsFile,
  137. $previousCommentOpenPtr,
  138. $previousCommentClosePtr,
  139. '@inheritdoc'
  140. );
  141. }
  142. /**
  143. * Validates whether @inheritdoc with braces [{@inheritdoc}] exists or not
  144. *
  145. * @param File $phpcsFile
  146. * @param int $previousCommentOpenPtr
  147. * @param int $previousCommentClosePtr
  148. */
  149. private function validateInheritdocAnnotationWithBracesExists(
  150. File $phpcsFile,
  151. int $previousCommentOpenPtr,
  152. int $previousCommentClosePtr
  153. ) : bool {
  154. return $this->validateInheritdocAnnotationExists(
  155. $phpcsFile,
  156. $previousCommentOpenPtr,
  157. $previousCommentClosePtr,
  158. '{@inheritdoc}'
  159. );
  160. }
  161. /**
  162. * Validates inheritdoc annotation exists
  163. *
  164. * @param File $phpcsFile
  165. * @param int $previousCommentOpenPtr
  166. * @param int $previousCommentClosePtr
  167. * @param string $inheritdocAnnotation
  168. * @return bool
  169. */
  170. private function validateInheritdocAnnotationExists(
  171. File $phpcsFile,
  172. int $previousCommentOpenPtr,
  173. int $previousCommentClosePtr,
  174. string $inheritdocAnnotation
  175. ) : bool {
  176. $tokens = $phpcsFile->getTokens();
  177. for ($ptr = $previousCommentOpenPtr; $ptr < $previousCommentClosePtr; $ptr++) {
  178. if (strtolower($tokens[$ptr]['content']) === $inheritdocAnnotation) {
  179. return true;
  180. }
  181. }
  182. return false;
  183. }
  184. /**
  185. * Validates if annotation exists for parameter in method annotation
  186. *
  187. * @param File $phpcsFile
  188. * @param int $argumentsCount
  189. * @param int $parametersCount
  190. * @param int $previousCommentOpenPtr
  191. * @param int $previousCommentClosePtr
  192. * @param int $stackPtr
  193. */
  194. private function validateParameterAnnotationForArgumentExists(
  195. File $phpcsFile,
  196. int $argumentsCount,
  197. int $parametersCount,
  198. int $previousCommentOpenPtr,
  199. int $previousCommentClosePtr,
  200. int $stackPtr
  201. ) : void {
  202. if ($argumentsCount > 0 && $parametersCount === 0) {
  203. $inheritdocAnnotationWithoutBracesExists = $this->validateInheritdocAnnotationWithoutBracesExists(
  204. $phpcsFile,
  205. $previousCommentOpenPtr,
  206. $previousCommentClosePtr
  207. );
  208. $inheritdocAnnotationWithBracesExists = $this->validateInheritdocAnnotationWithBracesExists(
  209. $phpcsFile,
  210. $previousCommentOpenPtr,
  211. $previousCommentClosePtr
  212. );
  213. if ($inheritdocAnnotationWithBracesExists) {
  214. $phpcsFile->addFixableError(
  215. '{@inheritdoc} does not import parameter annotation',
  216. $stackPtr,
  217. 'MethodArguments'
  218. );
  219. } elseif ($this->validateCommentBlockExists($phpcsFile, $previousCommentClosePtr, $stackPtr)
  220. && !$inheritdocAnnotationWithoutBracesExists
  221. ) {
  222. $phpcsFile->addFixableError(
  223. 'Missing @param for argument in method annotation',
  224. $stackPtr,
  225. 'MethodArguments'
  226. );
  227. }
  228. }
  229. }
  230. /**
  231. * Validates whether comment block have extra the parameters listed in method annotation
  232. *
  233. * @param File $phpcsFile
  234. * @param int $argumentsCount
  235. * @param int $parametersCount
  236. * @param int $stackPtr
  237. */
  238. private function validateCommentBlockDoesnotHaveExtraParameterAnnotation(
  239. File $phpcsFile,
  240. int $argumentsCount,
  241. int $parametersCount,
  242. int $stackPtr
  243. ) : void {
  244. if ($argumentsCount < $parametersCount && $argumentsCount > 0) {
  245. $phpcsFile->addFixableError(
  246. 'Extra @param found in method annotation',
  247. $stackPtr,
  248. 'MethodArguments'
  249. );
  250. } elseif ($argumentsCount > 0 && $argumentsCount != $parametersCount && $parametersCount != 0) {
  251. $phpcsFile->addFixableError(
  252. '@param is not found for one or more params in method annotation',
  253. $stackPtr,
  254. 'MethodArguments'
  255. );
  256. }
  257. }
  258. /**
  259. * Validates whether the argument name exists in method parameter annotation
  260. *
  261. * @param int $stackPtr
  262. * @param int $ptr
  263. * @param File $phpcsFile
  264. * @param array $methodArguments
  265. * @param array $paramDefinitions
  266. */
  267. private function validateArgumentNameInParameterAnnotationExists(
  268. int $stackPtr,
  269. int $ptr,
  270. File $phpcsFile,
  271. array $methodArguments,
  272. array $paramDefinitions
  273. ) : void {
  274. $parameterNames = $this->getMethodParameters($paramDefinitions);
  275. if (!in_array($methodArguments[$ptr], $parameterNames)) {
  276. $error = $methodArguments[$ptr]. ' parameter is missing in method annotation';
  277. $phpcsFile->addFixableError($error, $stackPtr, 'MethodArguments');
  278. }
  279. }
  280. /**
  281. * Validates whether parameter present in method signature
  282. *
  283. * @param int $ptr
  284. * @param int $paramDefinitionsArguments
  285. * @param array $methodArguments
  286. * @param File $phpcsFile
  287. * @param array $paramPointers
  288. */
  289. private function validateParameterPresentInMethodSignature(
  290. int $ptr,
  291. string $paramDefinitionsArguments,
  292. array $methodArguments,
  293. File $phpcsFile,
  294. array $paramPointers
  295. ) : void {
  296. if (!in_array($paramDefinitionsArguments, $methodArguments)) {
  297. $phpcsFile->addFixableError(
  298. $paramDefinitionsArguments . ' parameter is missing in method arguments signature',
  299. $paramPointers[$ptr],
  300. 'MethodArguments'
  301. );
  302. }
  303. }
  304. /**
  305. * Validates whether the parameters are in order or not in method annotation
  306. *
  307. * @param array $paramDefinitions
  308. * @param array $methodArguments
  309. * @param File $phpcsFile
  310. * @param array $paramPointers
  311. */
  312. private function validateParameterOrderIsCorrect(
  313. array $paramDefinitions,
  314. array $methodArguments,
  315. File $phpcsFile,
  316. array $paramPointers
  317. ) : void {
  318. $parameterNames = $this->getMethodParameters($paramDefinitions);
  319. $paramDefinitionsCount = count($paramDefinitions);
  320. for ($ptr = 0; $ptr < $paramDefinitionsCount; $ptr++) {
  321. if (isset($methodArguments[$ptr]) && isset($parameterNames[$ptr])
  322. && in_array($methodArguments[$ptr], $parameterNames)
  323. ) {
  324. if ($methodArguments[$ptr] != $parameterNames[$ptr]) {
  325. $phpcsFile->addFixableError(
  326. $methodArguments[$ptr].' parameter is not in order',
  327. $paramPointers[$ptr],
  328. 'MethodArguments'
  329. );
  330. }
  331. }
  332. }
  333. }
  334. /**
  335. * Validate whether duplicate annotation present in method annotation
  336. *
  337. * @param int $stackPtr
  338. * @param array $paramDefinitions
  339. * @param array $paramPointers
  340. * @param File $phpcsFile
  341. * @param array $methodArguments
  342. */
  343. private function validateDuplicateAnnotationDoesnotExists(
  344. int $stackPtr,
  345. array $paramDefinitions,
  346. array $paramPointers,
  347. File $phpcsFile,
  348. array $methodArguments
  349. ) : void {
  350. $argumentsCount = count($methodArguments);
  351. $parametersCount = count($paramPointers);
  352. if ($argumentsCount <= $parametersCount && $argumentsCount > 0) {
  353. $duplicateParameters = [];
  354. for ($i = 0; $i < sizeof($paramDefinitions); $i++) {
  355. if (isset($paramDefinitions[$i]['paramName'])) {
  356. $parameterContent = $paramDefinitions[$i]['paramName'];
  357. for ($j = $i + 1; $j < count($paramDefinitions); $j++) {
  358. if (isset($paramDefinitions[$j]['paramName'])
  359. && $parameterContent === $paramDefinitions[$j]['paramName']
  360. ) {
  361. $duplicateParameters[] = $parameterContent;
  362. }
  363. }
  364. }
  365. }
  366. foreach ($duplicateParameters as $value) {
  367. $phpcsFile->addFixableError(
  368. $value . ' duplicate found in method annotation',
  369. $stackPtr,
  370. 'MethodArguments'
  371. );
  372. }
  373. }
  374. }
  375. /**
  376. * Validate parameter annotation format is correct or not
  377. *
  378. * @param int $ptr
  379. * @param File $phpcsFile
  380. * @param array $methodArguments
  381. * @param array $paramDefinitions
  382. * @param array $paramPointers
  383. */
  384. private function validateParameterAnnotationFormatIsCorrect(
  385. int $ptr,
  386. File $phpcsFile,
  387. array $methodArguments,
  388. array $paramDefinitions,
  389. array $paramPointers
  390. ) : void {
  391. switch (count($paramDefinitions)) {
  392. case 0:
  393. $phpcsFile->addFixableError(
  394. 'Missing both type and parameter',
  395. $paramPointers[$ptr],
  396. 'MethodArguments'
  397. );
  398. break;
  399. case 1:
  400. if (preg_match('/^\$.*/', $paramDefinitions[0])) {
  401. $phpcsFile->addError(
  402. 'Type is not specified',
  403. $paramPointers[$ptr],
  404. 'MethodArguments'
  405. );
  406. }
  407. break;
  408. case 2:
  409. if ($this->isInvalidType($paramDefinitions[0])) {
  410. $phpcsFile->addFixableError(
  411. $paramDefinitions[0].' is not a valid PHP type',
  412. $paramPointers[$ptr],
  413. 'MethodArguments'
  414. );
  415. }
  416. $this->validateParameterPresentInMethodSignature(
  417. $ptr,
  418. ltrim($paramDefinitions[1], '&'),
  419. $methodArguments,
  420. $phpcsFile,
  421. $paramPointers
  422. );
  423. break;
  424. default:
  425. if (preg_match('/^\$.*/', $paramDefinitions[0])) {
  426. $phpcsFile->addError(
  427. 'Type is not specified',
  428. $paramPointers[$ptr],
  429. 'MethodArguments'
  430. );
  431. if ($this->isInvalidType($paramDefinitions[0])) {
  432. $phpcsFile->addFixableError(
  433. $paramDefinitions[0].' is not a valid PHP type',
  434. $paramPointers[$ptr],
  435. 'MethodArguments'
  436. );
  437. }
  438. }
  439. break;
  440. }
  441. }
  442. /**
  443. * Validate method parameter annotations
  444. *
  445. * @param int $stackPtr
  446. * @param array $paramDefinitions
  447. * @param array $paramPointers
  448. * @param File $phpcsFile
  449. * @param array $methodArguments
  450. * @param int $previousCommentOpenPtr
  451. * @param int $previousCommentClosePtr
  452. */
  453. private function validateMethodParameterAnnotations(
  454. int $stackPtr,
  455. array $paramDefinitions,
  456. array $paramPointers,
  457. File $phpcsFile,
  458. array $methodArguments,
  459. int $previousCommentOpenPtr,
  460. int $previousCommentClosePtr
  461. ) : void {
  462. $argumentCount = count($methodArguments);
  463. $paramCount = count($paramPointers);
  464. $this->validateParameterAnnotationForArgumentExists(
  465. $phpcsFile,
  466. $argumentCount,
  467. $paramCount,
  468. $previousCommentOpenPtr,
  469. $previousCommentClosePtr,
  470. $stackPtr
  471. );
  472. $this->validateCommentBlockDoesnotHaveExtraParameterAnnotation(
  473. $phpcsFile,
  474. $argumentCount,
  475. $paramCount,
  476. $stackPtr
  477. );
  478. $this->validateDuplicateAnnotationDoesnotExists(
  479. $stackPtr,
  480. $paramDefinitions,
  481. $paramPointers,
  482. $phpcsFile,
  483. $methodArguments
  484. );
  485. $this->validateParameterOrderIsCorrect(
  486. $paramDefinitions,
  487. $methodArguments,
  488. $phpcsFile,
  489. $paramPointers
  490. );
  491. for ($ptr = 0; $ptr < count($methodArguments); $ptr++) {
  492. $tokens = $phpcsFile->getTokens();
  493. if (isset($paramPointers[$ptr])) {
  494. $this->validateArgumentNameInParameterAnnotationExists(
  495. $stackPtr,
  496. $ptr,
  497. $phpcsFile,
  498. $methodArguments,
  499. $paramDefinitions
  500. );
  501. $paramContent = $tokens[$paramPointers[$ptr]+2]['content'];
  502. $paramContentExplode = explode(' ', $paramContent);
  503. $this->validateParameterAnnotationFormatIsCorrect(
  504. $ptr,
  505. $phpcsFile,
  506. $methodArguments,
  507. $paramContentExplode,
  508. $paramPointers
  509. );
  510. }
  511. }
  512. }
  513. /**
  514. * @inheritdoc
  515. */
  516. public function process(File $phpcsFile, $stackPtr)
  517. {
  518. $tokens = $phpcsFile->getTokens();
  519. $numTokens = count($tokens);
  520. $previousCommentOpenPtr = $phpcsFile->findPrevious(T_DOC_COMMENT_OPEN_TAG, $stackPtr-1, 0);
  521. $previousCommentClosePtr = $phpcsFile->findPrevious(T_DOC_COMMENT_CLOSE_TAG, $stackPtr-1, 0);
  522. if (!$this->validateCommentBlockExists($phpcsFile, $previousCommentClosePtr, $stackPtr)) {
  523. $phpcsFile->addError('Comment block is missing', $stackPtr, 'MethodArguments');
  524. return;
  525. }
  526. $openParenthesisPtr = $phpcsFile->findNext(T_OPEN_PARENTHESIS, $stackPtr+1, $numTokens);
  527. $closedParenthesisPtr = $phpcsFile->findNext(T_CLOSE_PARENTHESIS, $stackPtr+1, $numTokens);
  528. $methodArguments = $this->getMethodArguments($phpcsFile, $openParenthesisPtr, $closedParenthesisPtr);
  529. $paramPointers = $paramDefinitions = [];
  530. for ($tempPtr = $previousCommentOpenPtr; $tempPtr < $previousCommentClosePtr; $tempPtr++) {
  531. if (strtolower($tokens[$tempPtr]['content']) === '@param') {
  532. $paramPointers[] = $tempPtr;
  533. $paramAnnotationParts = explode(' ', $tokens[$tempPtr+2]['content']);
  534. if (count($paramAnnotationParts) === 1) {
  535. if ((preg_match('/^\$.*/', $paramAnnotationParts[0]))) {
  536. $paramDefinitions[] = [
  537. 'type' => null,
  538. 'paramName' => rtrim(ltrim($tokens[$tempPtr+2]['content'], '&'), ',')
  539. ];
  540. } else {
  541. $paramDefinitions[] = [
  542. 'type' => $tokens[$tempPtr+2]['content'],
  543. 'paramName' => null
  544. ];
  545. }
  546. } else {
  547. $paramDefinitions[] = [
  548. 'type' => $paramAnnotationParts[0],
  549. 'paramName' => rtrim(ltrim($paramAnnotationParts[1], '&'), ',')
  550. ];
  551. }
  552. }
  553. }
  554. $this->validateMethodParameterAnnotations(
  555. $stackPtr,
  556. $paramDefinitions,
  557. $paramPointers,
  558. $phpcsFile,
  559. $methodArguments,
  560. $previousCommentOpenPtr,
  561. $previousCommentClosePtr
  562. );
  563. }
  564. }