|
4 | 4 |
|
5 | 5 | namespace Doctrine\Sniffs\Spacing; |
6 | 6 |
|
7 | | -use PHP_CodeSniffer\Sniffs\Sniff; |
8 | 7 | use PHP_CodeSniffer\Files\File; |
| 8 | +use PHP_CodeSniffer\Sniffs\Sniff; |
9 | 9 |
|
10 | 10 | final class SpaceOnNotSniff implements Sniff |
11 | 11 | { |
12 | | - use EnsureSpaces; |
13 | | - |
14 | 12 | private const MESSAGE = 'There must be a single space %s a NOT operator; %d found'; |
15 | 13 |
|
16 | | - public function register() |
| 14 | + /** |
| 15 | + * @return int[] |
| 16 | + */ |
| 17 | + public function register() : array |
17 | 18 | { |
18 | 19 | return [\T_BOOLEAN_NOT]; |
19 | 20 | } |
20 | 21 |
|
21 | | - public function process(File $phpcsFile, $stackPtr) |
| 22 | + /** |
| 23 | + * @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint |
| 24 | + * @param int $stackPtr |
| 25 | + */ |
| 26 | + public function process(File $phpcsFile, $stackPtr) : void |
22 | 27 | { |
23 | 28 | $tokens = $phpcsFile->getTokens(); |
24 | 29 |
|
25 | 30 | $this->ensureSpaceBefore($phpcsFile, $tokens, $stackPtr, self::MESSAGE); |
26 | 31 | $this->ensureSpaceAfter($phpcsFile, $tokens, $stackPtr, self::MESSAGE); |
27 | 32 | } |
| 33 | + |
| 34 | + /** |
| 35 | + * @param mixed[][] $tokens |
| 36 | + */ |
| 37 | + protected function ensureSpaceBefore(File $file, array $tokens, int $position, string $message) : void |
| 38 | + { |
| 39 | + $spacing = $this->numberOfSpaces($tokens, $position - 1); |
| 40 | + |
| 41 | + if ($spacing === 1) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + if ( ! $file->addFixableError($message, $position, 'before', ['before', $spacing])) { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + if ($spacing === 0) { |
| 50 | + $file->fixer->addContentBefore($position, ' '); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + $file->fixer->replaceToken($position - 1, ' '); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @param mixed[][] $tokens |
| 59 | + */ |
| 60 | + protected function ensureSpaceAfter(File $file, array $tokens, int $position, string $message) : void |
| 61 | + { |
| 62 | + $spacing = $this->numberOfSpaces($tokens, $position + 1); |
| 63 | + |
| 64 | + if ($spacing === 1) { |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + if ( ! $file->addFixableError($message, $position, 'after', ['after', $spacing])) { |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + if ($spacing === 0) { |
| 73 | + $file->fixer->addContent($position, ' '); |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + $file->fixer->replaceToken($position + 1, ' '); |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * @param mixed[][] $tokens |
| 82 | + */ |
| 83 | + private function numberOfSpaces(array $tokens, int $position) : int |
| 84 | + { |
| 85 | + $token = $tokens[$position]; |
| 86 | + |
| 87 | + return $token['code'] === T_WHITESPACE ? $token['length'] : 0; |
| 88 | + } |
28 | 89 | } |
0 commit comments