/
NoLeadingSlashInGlobalNamespaceFixer.php
64 lines (53 loc) · 1.74 KB
/
NoLeadingSlashInGlobalNamespaceFixer.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
<?php
declare(strict_types = 1);
namespace PhpCsFixerCustomFixers\Fixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
final class NoLeadingSlashInGlobalNamespaceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'When in global namespace there must be no leading slash for class.',
[new CodeSample('<?php
$x = new \Foo();
namespace Bar;
$y = new \Baz();
')]
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(T_NS_SEPARATOR);
}
public function isRisky(): bool
{
return false;
}
public function fix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(T_NAMESPACE)) {
return;
}
if (!$token->isGivenKind(T_NS_SEPARATOR)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(T_STRING)) {
continue;
}
$nextIndex = $tokens->getTokenNotOfKindSibling($index, 1, [[T_COMMENT], [T_DOC_COMMENT], [T_NS_SEPARATOR], [T_STRING], [T_WHITESPACE]]);
if ($tokens[$prevIndex]->isGivenKind(T_NEW) || $tokens[$nextIndex]->isGivenKind(T_DOUBLE_COLON)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
}
public function getPriority(): int
{
// must be run before PhpdocToCommentFixer
return 26;
}
}