|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace DatacodeStandard\Sniffs\Classes; |
| 6 | + |
| 7 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 8 | +use PHP_CodeSniffer\Files\File; |
| 9 | + |
| 10 | +/** |
| 11 | + * Ensures no blank line after class open closure |
| 12 | + */ |
| 13 | +class OpeningBraceSniff implements Sniff { |
| 14 | + |
| 15 | + public function register() { |
| 16 | + return [ |
| 17 | + T_CLASS, |
| 18 | + ]; |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Processes this test, when one of its tokens is encountered. |
| 23 | + * |
| 24 | + * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. |
| 25 | + * @param integer $stackPtr The position of the current token in the stack passed in $tokens. |
| 26 | + * |
| 27 | + * @return int |
| 28 | + */ |
| 29 | + public function process(File $phpcsFile, $stackPtr) { |
| 30 | + $tokens = $phpcsFile->getTokens(); |
| 31 | + $opener = $tokens[$stackPtr]['scope_opener']; |
| 32 | + $nextAfterOpen = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true); |
| 33 | + |
| 34 | + if ($tokens[$nextAfterOpen]['line'] > ($tokens[$opener]['line'] + 1)) { |
| 35 | + // Opening brace is on a new line, so there must be no blank line after it. |
| 36 | + $error = 'Opening brace must not be succeeded by a blank line'; |
| 37 | + $fix = $phpcsFile->addFixableError($error, $opener, 'OpenBraceFollowedByBlankLine'); |
| 38 | + |
| 39 | + if ($fix === true) { |
| 40 | + $phpcsFile->fixer->beginChangeset(); |
| 41 | + for ($x = ($opener + 1); $x < $nextAfterOpen; $x++) { |
| 42 | + if ($tokens[$x]['line'] === $tokens[$opener]['line']) { |
| 43 | + // Maintain existing newline. |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + if ($tokens[$x]['line'] === $tokens[$nextAfterOpen]['line']) { |
| 48 | + // Maintain existing indent. |
| 49 | + break; |
| 50 | + } |
| 51 | + |
| 52 | + $phpcsFile->fixer->replaceToken($x, ''); |
| 53 | + } |
| 54 | + |
| 55 | + $phpcsFile->fixer->endChangeset(); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return ($phpcsFile->numTokens + 1); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments