-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
CaseCommentIndentationFixer.php
112 lines (90 loc) · 3.22 KB
/
CaseCommentIndentationFixer.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
110
111
112
<?php
declare(strict_types=1);
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao\EasyCodingStandard\Fixer;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @see https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/6490
*/
final class CaseCommentIndentationFixer extends AbstractFixer
{
use IndentationFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Comments before a "case" statement must be properly indented.',
[
new CodeSample(
<<<'EOT'
<?php
switch {
// First case
case 1:
break;
// Second case
case 2:
break;
}
EOT,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([T_CASE, T_DEFAULT]);
}
public function getPriority(): int
{
// must be run after StatementIndentationFixer
return -10;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 1, $count = \count($tokens); $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind([T_CASE, T_DEFAULT])) {
continue;
}
$prevMeaningful = $tokens->getPrevNonWhitespace($index);
if (!$tokens[$prevMeaningful]->isGivenKind(T_COMMENT)) {
continue;
}
// If there is more than one line break between the comment and the "case"
// statement, the two do not belong to each other.
if (substr_count($tokens->generatePartialCode($prevMeaningful, $index), "\n") > 1) {
continue;
}
$indentCase = $this->getIndent($tokens, $index);
$indentComment = $this->getIndent($tokens, $prevMeaningful, false);
if ($indentCase === $indentComment) {
continue;
}
$indent = ltrim($indentCase, "\n");
$replacement = rtrim($indentComment, "\t ").$indent;
$i = $prevMeaningful - 1;
$tokens->offsetSet($prevMeaningful - 1, new Token([T_WHITESPACE, $replacement]));
// Handle multi-line comments
while (true) {
$prevComment = $tokens->getPrevNonWhitespace($i);
if (!$tokens[$prevComment]->isGivenKind(T_COMMENT)) {
break;
}
$indentComment = $this->getIndent($tokens, $prevComment, false);
$replacement = rtrim($indentComment, "\t ").$indent;
$i = $prevComment - 1;
$tokens->offsetSet($prevComment - 1, new Token([T_WHITESPACE, $replacement]));
}
}
}
}