forked from PHP-CS-Fixer/PHP-CS-Fixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TernaryToElvisOperatorFixer.php
217 lines (177 loc) · 6.13 KB
/
TernaryToElvisOperatorFixer.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <[email protected]>
* Dariusz Rumiński <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
final class TernaryToElvisOperatorFixer extends AbstractFixer
{
/**
* Lower precedence and other valid preceding tokens.
*
* Ordered by most common types first.
*
* @var list<array{int}|string>
*/
private const VALID_BEFORE_ENDTYPES = [
'=',
[T_OPEN_TAG],
[T_OPEN_TAG_WITH_ECHO],
'(',
',',
';',
'[',
'{',
'}',
[CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN],
[T_AND_EQUAL], // &=
[T_CONCAT_EQUAL], // .=
[T_DIV_EQUAL], // /=
[T_MINUS_EQUAL], // -=
[T_MOD_EQUAL], // %=
[T_MUL_EQUAL], // *=
[T_OR_EQUAL], // |=
[T_PLUS_EQUAL], // +=
[T_POW_EQUAL], // **=
[T_SL_EQUAL], // <<=
[T_SR_EQUAL], // >>=
[T_XOR_EQUAL], // ^=
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Use the Elvis operator `?:` where possible.',
[
new CodeSample(
"<?php\n\$foo = \$foo ? \$foo : 1;\n"
),
new CodeSample(
"<?php \$foo = \$bar[a()] ? \$bar[a()] : 1; # \"risky\" sample, \"a()\" only gets called once after fixing\n"
),
],
null,
'Risky when relying on functions called on both sides of the `?` operator.'
);
}
/**
* {@inheritdoc}
*
* Must run before NoTrailingWhitespaceFixer, TernaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('?');
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$blockEdgeDefinitions = Tokens::getBlockEdgeDefinitions();
for ($index = \count($tokens) - 5; $index > 1; --$index) {
if (!$tokens[$index]->equals('?')) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->equals(':')) {
continue; // Elvis is alive!
}
// get and check what is before the `?` operator
$beforeOperator = $this->getBeforeOperator($tokens, $index, $blockEdgeDefinitions);
if (null === $beforeOperator) {
continue; // contains something we cannot fix because of priorities
}
// get what is after the `?` token
$afterOperator = $this->getAfterOperator($tokens, $index);
// if before and after the `?` operator are the same (in meaningful matter), clear after
if (RangeAnalyzer::rangeEqualsRange($tokens, $beforeOperator, $afterOperator)) {
$this->clearMeaningfulFromRange($tokens, $afterOperator);
}
}
}
/**
* @return null|array{start: int, end: int} null if contains ++/-- operator
*/
private function getBeforeOperator(Tokens $tokens, int $index, array $blockEdgeDefinitions): ?array
{
$index = $tokens->getPrevMeaningfulToken($index);
$before = ['end' => $index];
while (!$tokens[$index]->equalsAny(self::VALID_BEFORE_ENDTYPES)) {
if ($tokens[$index]->isGivenKind([T_INC, T_DEC])) {
return null;
}
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null === $blockType || $blockType['isStart']) {
$before['start'] = $index;
$index = $tokens->getPrevMeaningfulToken($index);
continue;
}
$blockType = $blockEdgeDefinitions[$blockType['type']];
$openCount = 1;
do {
$index = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$index]->isGivenKind([T_INC, T_DEC])) {
return null;
}
if ($tokens[$index]->equals($blockType['start'])) {
++$openCount;
continue;
}
if ($tokens[$index]->equals($blockType['end'])) {
--$openCount;
}
} while (1 >= $openCount);
$before['start'] = $index;
$index = $tokens->getPrevMeaningfulToken($index);
}
if (!isset($before['start'])) {
return null;
}
return $before;
}
/**
* @return array{start: int, end: int}
*/
private function getAfterOperator(Tokens $tokens, int $index): array
{
$index = $tokens->getNextMeaningfulToken($index);
$after = ['start' => $index];
while (!$tokens[$index]->equals(':')) {
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
}
$after['end'] = $index;
$index = $tokens->getNextMeaningfulToken($index);
}
return $after;
}
/**
* @param array{start: int, end: int} $range
*/
private function clearMeaningfulFromRange(Tokens $tokens, array $range): void
{
// $range['end'] must be meaningful!
for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
}
}