-
-
Notifications
You must be signed in to change notification settings - Fork 170
/
ReturnTypehintSpacingSniff.php
56 lines (45 loc) · 1.86 KB
/
ReturnTypehintSpacingSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Typehints;
use SlevomatCodingStandard\Helpers\TokenHelper;
class ReturnTypehintSpacingSniff implements \PHP_CodeSniffer_Sniff
{
const CODE_NO_SPACE_BETWEEN_COLON_AND_TYPE = 'NoSpaceBetweenColonAndType';
const CODE_MULTIPLE_SPACES_BETWEEN_COLON_AND_TYPE = 'MultipleSpacesBetweenColonAndType';
const CODE_WHITESPACE_BEFORE_COLON = 'WhitespaceBeforeColon';
/**
* @return int[]
*/
public function register(): array
{
return [
T_RETURN_TYPE,
];
}
/**
* @phpcsSuppress SlevomatCodingStandard.Typehints.TypeHintDeclaration.missingParameterTypeHint
* @param \PHP_CodeSniffer_File $phpcsFile
* @param int $returnTypePointer
*/
public function process(\PHP_CodeSniffer_File $phpcsFile, $returnTypePointer)
{
$tokens = $phpcsFile->getTokens();
$beforeNamePointer = TokenHelper::findPreviousExcluding($phpcsFile, [T_NS_SEPARATOR, T_STRING], $returnTypePointer - 1);
$beforeNameToken = $tokens[$beforeNamePointer];
$afterColonMessage = 'There must be exactly one space before return typehint.';
if ($beforeNameToken['code'] === T_COLON) {
$phpcsFile->addError($afterColonMessage, $returnTypePointer, self::CODE_NO_SPACE_BETWEEN_COLON_AND_TYPE);
$colonPointer = $beforeNamePointer;
} elseif ($beforeNameToken['code'] === T_WHITESPACE) {
if ($beforeNameToken['content'] !== ' ') {
$phpcsFile->addError($afterColonMessage, $returnTypePointer, self::CODE_MULTIPLE_SPACES_BETWEEN_COLON_AND_TYPE);
}
$colonPointer = $phpcsFile->findPrevious(T_COLON, $beforeNamePointer - 1);
} else {
return;
}
$previousPointer = $colonPointer - 1;
if ($tokens[$previousPointer]['code'] !== T_CLOSE_PARENTHESIS) {
$phpcsFile->addError('There must be no whitespace between closing parenthesis and return type colon.', $returnTypePointer, self::CODE_WHITESPACE_BEFORE_COLON);
}
}
}