MethodAnnotationStructureSniff.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 structure of public, private, protected method annotations
  12. */
  13. class MethodAnnotationStructureSniff implements Sniff
  14. {
  15. /**
  16. * @var AnnotationFormatValidator
  17. */
  18. private $annotationFormatValidator;
  19. /**
  20. * AnnotationStructureSniff constructor.
  21. */
  22. public function __construct()
  23. {
  24. $this->annotationFormatValidator = new AnnotationFormatValidator();
  25. }
  26. /**
  27. * @inheritdoc
  28. */
  29. public function register()
  30. {
  31. return [
  32. T_FUNCTION
  33. ];
  34. }
  35. /**
  36. * @inheritdoc
  37. */
  38. public function process(File $phpcsFile, $stackPtr)
  39. {
  40. $tokens = $phpcsFile->getTokens();
  41. $commentStartPtr = $phpcsFile->findPrevious(T_DOC_COMMENT_OPEN_TAG, ($stackPtr), 0);
  42. $commentEndPtr = $phpcsFile->findPrevious(T_DOC_COMMENT_CLOSE_TAG, ($stackPtr), 0);
  43. $commentCloserPtr = $tokens[$commentStartPtr]['comment_closer'];
  44. $functionPtrContent = $tokens[$stackPtr+2]['content'] ;
  45. if (preg_match('/(?i)__construct/', $functionPtrContent)) {
  46. return;
  47. }
  48. $emptyTypeTokens = [
  49. T_DOC_COMMENT_WHITESPACE,
  50. T_DOC_COMMENT_STAR
  51. ];
  52. $shortPtr = $phpcsFile->findNext($emptyTypeTokens, $commentStartPtr + 1, $commentCloserPtr, true);
  53. if ($shortPtr === false) {
  54. $error = 'Annotation block is empty';
  55. $phpcsFile->addError($error, $commentStartPtr, 'MethodAnnotation');
  56. } else {
  57. $this->annotationFormatValidator->validateDescriptionFormatStructure(
  58. $phpcsFile,
  59. $commentStartPtr,
  60. (int) $shortPtr,
  61. $commentEndPtr,
  62. $emptyTypeTokens
  63. );
  64. if (empty($tokens[$commentStartPtr]['comment_tags'])) {
  65. return;
  66. }
  67. $this->annotationFormatValidator->validateTagsSpacingFormat(
  68. $phpcsFile,
  69. $commentStartPtr,
  70. $emptyTypeTokens
  71. );
  72. $this->annotationFormatValidator->validateTagGroupingFormat($phpcsFile, $commentStartPtr);
  73. }
  74. }
  75. }