|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * BigBite Coding Standards. |
| 4 | + * |
| 5 | + * @package BigBiteCS\BigBite |
| 6 | + * @link https://github.com/bigbite/phpcs-config |
| 7 | + * @license https://opensource.org/licenses/MIT MIT |
| 8 | + */ |
| 9 | + |
| 10 | +namespace BigBiteCS\BigBite\Sniffs\Objects; |
| 11 | + |
| 12 | +use PHP_CodeSniffer\Files\File; |
| 13 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 14 | + |
| 15 | +/** |
| 16 | + * Ensures a blank line between the last content and closing brace of an object declaration. |
| 17 | + */ |
| 18 | +final class NewLineBeforeClosingBraceSniff implements Sniff { |
| 19 | + |
| 20 | + /** |
| 21 | + * A list of tokenizers this sniff supports. |
| 22 | + * |
| 23 | + * @var array<int,string> |
| 24 | + */ |
| 25 | + public $supportedTokenizers = array( |
| 26 | + 'PHP', |
| 27 | + ); |
| 28 | + |
| 29 | + /** |
| 30 | + * Returns an array of tokens this test wants to listen for. |
| 31 | + * |
| 32 | + * @return array<int,int|string> |
| 33 | + */ |
| 34 | + public function register() { |
| 35 | + return array( |
| 36 | + \T_CLASS, |
| 37 | + \T_ENUM, |
| 38 | + \T_INTERFACE, |
| 39 | + \T_TRAIT, |
| 40 | + ); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Processes this test, when one of its tokens is encountered. |
| 45 | + * |
| 46 | + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. |
| 47 | + * @param int $stackPtr The position of the current token |
| 48 | + * in the stack passed in $tokens. |
| 49 | + * |
| 50 | + * @return void |
| 51 | + */ |
| 52 | + public function process( File $phpcsFile, $stackPtr ) { |
| 53 | + $tokens = $phpcsFile->getTokens(); |
| 54 | + |
| 55 | + $openingLineNo = $tokens[ $stackPtr ]['line']; |
| 56 | + $closingBrace = $tokens[ $stackPtr ]['scope_closer']; |
| 57 | + $closingLineNo = $tokens[ $closingBrace ]['line']; |
| 58 | + |
| 59 | + // Other sniffs will handle objects with empty or malformed bodies. |
| 60 | + if ( $openingLineNo === $closingLineNo || ( $openingLineNo + 1 ) === $closingLineNo ) { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + $prevContent = $phpcsFile->findPrevious( \T_WHITESPACE, ( $closingBrace - 1 ), null, true ); |
| 65 | + |
| 66 | + if ( ( $closingLineNo - 2 ) === $tokens[ $prevContent ]['line'] ) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + $error = 'There must be exactly one blank line between the body of a %s and its closing brace.'; |
| 71 | + $data = array( $tokens[ $stackPtr ]['content'] ); |
| 72 | + $fix = $phpcsFile->addFixableError( $error, $closingBrace, 'NotFound', $data ); |
| 73 | + |
| 74 | + if ( true !== $fix ) { |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + $phpcsFile->fixer->beginChangeset(); |
| 79 | + $phpcsFile->fixer->addNewlineBefore( $closingBrace ); |
| 80 | + $phpcsFile->fixer->endChangeset(); |
| 81 | + } |
| 82 | +} |
0 commit comments