|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Space48\CodeQuality\RuleSets\PhpCs\Space48Extra\Sniffs; |
| 4 | + |
| 5 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 6 | +use PHP_CodeSniffer\Files\File as CodeSnifferFile; |
| 7 | + |
| 8 | +class BlankLineBeforeReturnSniff implements Sniff |
| 9 | +{ |
| 10 | + /** |
| 11 | + * A list of tokenizers this sniff supports. |
| 12 | + * |
| 13 | + * @var array |
| 14 | + */ |
| 15 | + public $supportedTokenizers = array( |
| 16 | + 'PHP', |
| 17 | + 'JS', |
| 18 | + ); |
| 19 | + |
| 20 | + /** |
| 21 | + * Returns an array of tokens this test wants to listen for. |
| 22 | + * |
| 23 | + * @return array |
| 24 | + */ |
| 25 | + public function register() |
| 26 | + { |
| 27 | + return array(T_RETURN); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Processes this test, when one of its tokens is encountered. |
| 32 | + * |
| 33 | + * @param CodeSnifferFile $phpcsFile All the tokens found in the document. |
| 34 | + * @param int $stackPtr The position of the current token in |
| 35 | + * the stack passed in $tokens. |
| 36 | + * |
| 37 | + * @return void |
| 38 | + */ |
| 39 | + public function process(CodeSnifferFile $phpcsFile, $stackPtr) |
| 40 | + { |
| 41 | + $tokens = $phpcsFile->getTokens(); |
| 42 | + $current = $stackPtr; |
| 43 | + $previousLine = $tokens[$stackPtr]['line'] - 1; |
| 44 | + $prevLineTokens = array(); |
| 45 | + |
| 46 | + while ($current >= 0 && $tokens[$current]['line'] >= $previousLine) { |
| 47 | + if ($tokens[$current]['line'] == $previousLine |
| 48 | + && $tokens[$current]['type'] !== 'T_WHITESPACE' |
| 49 | + && $tokens[$current]['type'] !== 'T_COMMENT' |
| 50 | + ) { |
| 51 | + $prevLineTokens[] = $tokens[$current]['type']; |
| 52 | + } |
| 53 | + $current--; |
| 54 | + } |
| 55 | + |
| 56 | + if (isset($prevLineTokens[0]) |
| 57 | + && ($prevLineTokens[0] === 'T_OPEN_CURLY_BRACKET' |
| 58 | + || $prevLineTokens[0] === 'T_COLON') |
| 59 | + ) { |
| 60 | + return; |
| 61 | + } else if (count($prevLineTokens) > 0) { |
| 62 | + $fix = $phpcsFile->addFixableError( |
| 63 | + 'Missing blank line before return statement', |
| 64 | + $stackPtr, |
| 65 | + 'MissedBlankLineBeforeRetrun' |
| 66 | + ); |
| 67 | + |
| 68 | + if ($fix === true) { |
| 69 | + $phpcsFile->fixer->beginChangeset(); |
| 70 | + $i = 1; |
| 71 | + while($tokens[$stackPtr-$i]['type'] == "T_WHITESPACE") { |
| 72 | + $i++; |
| 73 | + } |
| 74 | + $phpcsFile->fixer->addNewLine($stackPtr-$i); |
| 75 | + $phpcsFile->fixer->endChangeset(); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return; |
| 80 | + } |
| 81 | +} |
0 commit comments