|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace SymfonyCustom\Sniffs\Namespaces; |
| 4 | + |
| 5 | +use PHP_CodeSniffer\Files\File; |
| 6 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 7 | + |
| 8 | +/** |
| 9 | + * Ensure there is a blank line before namespace. |
| 10 | + * PSR2 checks only for blank line after namespace. |
| 11 | + */ |
| 12 | +class NamespaceDeclarationSniff implements Sniff |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Returns an array of tokens this test wants to listen for. |
| 16 | + * |
| 17 | + * @return array |
| 18 | + */ |
| 19 | + public function register() |
| 20 | + { |
| 21 | + return [T_NAMESPACE]; |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Processes this test, when one of its tokens is encountered. |
| 26 | + * |
| 27 | + * @param File $phpcsFile The file being scanned. |
| 28 | + * @param int $stackPtr The position of the current token in the stack passed in $tokens. |
| 29 | + * |
| 30 | + * @return void |
| 31 | + */ |
| 32 | + public function process(File $phpcsFile, $stackPtr) |
| 33 | + { |
| 34 | + $tokens = $phpcsFile->getTokens(); |
| 35 | + |
| 36 | + for ($i = $stackPtr - 1; $i > 0; $i--) { |
| 37 | + if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) { |
| 38 | + continue; |
| 39 | + } |
| 40 | + |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + // The $i var now points to the last token on the line before the |
| 45 | + // namespace declaration, which must be a blank line. |
| 46 | + $previous = $phpcsFile->findPrevious(T_WHITESPACE, $i, null, true); |
| 47 | + if (false === $previous) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + $diff = ($tokens[$i]['line'] - $tokens[$previous]['line']); |
| 52 | + if (1 === $diff) { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + if ($diff < 0) { |
| 57 | + $diff = 0; |
| 58 | + } |
| 59 | + |
| 60 | + $error = 'There must be one blank line before the namespace declaration'; |
| 61 | + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'BlankLineBefore'); |
| 62 | + |
| 63 | + if (true === $fix) { |
| 64 | + if (0 === $diff) { |
| 65 | + $phpcsFile->fixer->addNewlineBefore($stackPtr); |
| 66 | + } else { |
| 67 | + $phpcsFile->fixer->beginChangeset(); |
| 68 | + for ($x = $stackPtr - 1; $x > $previous; $x--) { |
| 69 | + if ($tokens[$x]['line'] === $tokens[$previous]['line']) { |
| 70 | + break; |
| 71 | + } |
| 72 | + |
| 73 | + $phpcsFile->fixer->replaceToken($x, ''); |
| 74 | + } |
| 75 | + |
| 76 | + $phpcsFile->fixer->addNewlineBefore($stackPtr); |
| 77 | + $phpcsFile->fixer->endChangeset(); |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments