/
NoUselessCommentFixer.php
109 lines (94 loc) · 2.99 KB
/
NoUselessCommentFixer.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/*
* This file is part of PHP CS Fixer: custom fixers.
*
* (c) 2018-2020 Kuba Werłos
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace PhpCsFixerCustomFixers\Fixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
final class NoUselessCommentFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must be no comment like "Class Foo".',
[
new CodeSample('<?php
/**
* Class Foo
* Class to do something
*/
class Foo {
/**
* Get bar
*/
function getBar() {}
}
'),
]
);
}
/**
* Must run before NoEmptyCommentFixer, NoEmptyPhpdocFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer.
*/
public function getPriority(): int
{
return 4;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([T_COMMENT, T_DOC_COMMENT]);
}
public function isRisky(): bool
{
return false;
}
public function fix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index > 0; $index--) {
/** @var Token $token */
$token = $tokens[$index];
if (!$token->isGivenKind([T_COMMENT, T_DOC_COMMENT])) {
continue;
}
$nextIndex = $tokens->getTokenNotOfKindSibling(
$index,
1,
[[T_WHITESPACE], [T_COMMENT], [T_ABSTRACT], [T_FINAL], [T_PUBLIC], [T_PROTECTED], [T_PRIVATE], [T_STATIC]]
);
if ($nextIndex === null) {
continue;
}
/** @var Token $nextToken */
$nextToken = $tokens[$nextIndex];
if ($nextToken->isGivenKind([T_CLASS, T_INTERFACE, T_TRAIT])) {
$newContent = Preg::replace(
'/\R?(?<=\n|\r|\r\n|^#|^\/\/|^\/\*|^\/\*\*)\h+\**\h*(class|interface|trait)\h+[A-Za-z0-9\\\\_]+.?(?=\R|$)/i',
'',
$token->getContent()
);
} elseif ($nextToken->isGivenKind(T_FUNCTION)) {
$newContent = Preg::replace(
'/\R?(?<=\n|\r|\r\n|^#|^\/\/|^\/\*|^\/\*\*)\h+\**\h*((adds?|gets?|removes?|sets?)\h+[A-Za-z0-9\\\\_]+|([A-Za-z0-9\\\\_]+\h+)?constructor).?(?=\R|$)/i',
'',
$token->getContent()
);
} else {
continue;
}
if ($newContent === $token->getContent()) {
continue;
}
$tokens[$index] = new Token([$token->getId(), $newContent]);
}
}
}