/
RequireAttributeAfterDocCommentSniff.php
86 lines (65 loc) · 2.5 KB
/
RequireAttributeAfterDocCommentSniff.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php declare(strict_types = 1);
namespace SlevomatCodingStandard\Sniffs\Attributes;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use SlevomatCodingStandard\Helpers\AttributeHelper;
use SlevomatCodingStandard\Helpers\FixerHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use const T_ATTRIBUTE;
use const T_ATTRIBUTE_END;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_WHITESPACE;
class RequireAttributeAfterDocCommentSniff implements Sniff
{
public const CODE_ATTRIBUTE_BEFORE_DOC_COMMENT = 'AttributeBeforeDocComment';
/**
* @return array<int, (int|string)>
*/
public function register(): array
{
return [T_ATTRIBUTE];
}
/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
* @param int $attributeOpenerPointer
*/
public function process(File $phpcsFile, $attributeOpenerPointer): void
{
if (!AttributeHelper::isValidAttribute($phpcsFile, $attributeOpenerPointer)) {
return;
}
$tokens = $phpcsFile->getTokens();
$docCommentOpenerPointer = TokenHelper::findNextExcluding(
$phpcsFile,
T_WHITESPACE,
$tokens[$attributeOpenerPointer]['attribute_closer'] + 1
);
if ($tokens[$docCommentOpenerPointer]['code'] !== T_DOC_COMMENT_OPEN_TAG) {
return;
}
$docCommentStartPointer = TokenHelper::findFirstTokenOnLine($phpcsFile, $docCommentOpenerPointer);
$docCommentEndPointer = TokenHelper::findLastTokenOnLine($phpcsFile, $tokens[$docCommentOpenerPointer]['comment_closer']);
$docComment = TokenHelper::getContent($phpcsFile, $docCommentStartPointer, $docCommentEndPointer);
$firstAttributeOpenerPointer = $attributeOpenerPointer;
do {
$nonWhitespacePointerBefore = TokenHelper::findPreviousNonWhitespace($phpcsFile, $firstAttributeOpenerPointer - 1);
if ($tokens[$nonWhitespacePointerBefore]['code'] !== T_ATTRIBUTE_END) {
break;
}
$firstAttributeOpenerPointer = $tokens[$nonWhitespacePointerBefore]['attribute_opener'];
} while (true);
$attributeStartPointer = TokenHelper::findFirstTokenOnLine($phpcsFile, $firstAttributeOpenerPointer);
$fix = $phpcsFile->addFixableError(
'Attribute should be placed before documentation comment.',
$attributeOpenerPointer,
self::CODE_ATTRIBUTE_BEFORE_DOC_COMMENT
);
if (!$fix) {
return;
}
$phpcsFile->fixer->beginChangeset();
$phpcsFile->fixer->addContentBefore($attributeStartPointer, $docComment);
FixerHelper::removeBetweenIncluding($phpcsFile, $docCommentStartPointer, $docCommentEndPointer);
$phpcsFile->fixer->endChangeset();
}
}