|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace PSR2R\Sniffs\Commenting; |
| 4 | + |
| 5 | +use PHP_CodeSniffer\Files\File; |
| 6 | +use PSR2R\Tools\AbstractSniff; |
| 7 | + |
| 8 | +/** |
| 9 | + * No empty phpdoc tags and no empty @ tag. |
| 10 | + */ |
| 11 | +class DocBlockNoEmptySniff extends AbstractSniff { |
| 12 | + |
| 13 | + /** |
| 14 | + * @inheritDoc |
| 15 | + */ |
| 16 | + public function register() { |
| 17 | + return [ |
| 18 | + T_DOC_COMMENT_OPEN_TAG, |
| 19 | + ]; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * @inheritDoc |
| 24 | + */ |
| 25 | + public function process(File $phpcsFile, $stackPtr) { |
| 26 | + $tokens = $phpcsFile->getTokens(); |
| 27 | + |
| 28 | + if (empty($tokens[$stackPtr]['comment_closer'])) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + $endIndex = $tokens[$stackPtr]['comment_closer']; |
| 33 | + |
| 34 | + $this->assertNonEmptyDocBlock($phpcsFile, $stackPtr, $endIndex); |
| 35 | + $this->assertNoEmptyTag($phpcsFile, $stackPtr, $endIndex); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @param \PHP_CodeSniffer\Files\File $phpcsFile |
| 40 | + * @param int $stackPtr |
| 41 | + * @param int $endIndex |
| 42 | + * |
| 43 | + * @return void |
| 44 | + */ |
| 45 | + protected function assertNonEmptyDocBlock(File $phpcsFile, $stackPtr, $endIndex) { |
| 46 | + $nextIndex = $phpcsFile->findNext([T_WHITESPACE, T_DOC_COMMENT_WHITESPACE, T_DOC_COMMENT_STAR], $stackPtr + 1, $endIndex - 1, true); |
| 47 | + if ($nextIndex) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + $fix = $phpcsFile->addFixableError('There should be no empty docblocks.', $stackPtr, 'Superfluous'); |
| 52 | + if ($fix) { |
| 53 | + for ($i = $stackPtr; $i <= $endIndex; $i++) { |
| 54 | + $phpcsFile->fixer->replaceToken($i, ''); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * @param \PHP_CodeSniffer\Files\File $phpcsFile |
| 61 | + * @param int $stackPtr |
| 62 | + * @param int $endIndex |
| 63 | + * |
| 64 | + * @return void |
| 65 | + */ |
| 66 | + protected function assertNoEmptyTag(File $phpcsFile, $stackPtr, $endIndex) { |
| 67 | + $tokens = $phpcsFile->getTokens(); |
| 68 | + |
| 69 | + $index = $stackPtr; |
| 70 | + while ($index < $endIndex) { |
| 71 | + $nextIndex = $phpcsFile->findNext([T_DOC_COMMENT_STRING], $index + 1, $endIndex); |
| 72 | + if (!$nextIndex) { |
| 73 | + return; |
| 74 | + } |
| 75 | + $index = $nextIndex; |
| 76 | + |
| 77 | + if (empty($tokens[$index]['content']) || $tokens[$index]['content'] !== '@') { |
| 78 | + continue; |
| 79 | + } |
| 80 | + |
| 81 | + $fix = $phpcsFile->addFixableError('Empty Doc Block Tag', $index, 'Empty'); |
| 82 | + if (!$fix) { |
| 83 | + continue; |
| 84 | + } |
| 85 | + |
| 86 | + $phpcsFile->fixer->replaceToken($index, ''); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | +} |
0 commit comments