forked from PHP-CS-Fixer/PHP-CS-Fixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LambdaNotUsedImportFixer.php
346 lines (268 loc) · 11.4 KB
/
LambdaNotUsedImportFixer.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
<?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\FunctionNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
final class LambdaNotUsedImportFixer extends AbstractFixer
{
/**
* @var ArgumentsAnalyzer
*/
private $argumentsAnalyzer;
/**
* @var FunctionsAnalyzer
*/
private $functionAnalyzer;
/**
* @var TokensAnalyzer
*/
private $tokensAnalyzer;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Lambda must not import variables it doesn\'t use.',
[new CodeSample("<?php\n\$foo = function() use (\$bar) {};\n")]
);
}
/**
* {@inheritdoc}
*
* Must run before MethodArgumentSpaceFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer.
*/
public function getPriority(): int
{
return 31;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([T_FUNCTION, CT::T_USE_LAMBDA]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->argumentsAnalyzer = new ArgumentsAnalyzer();
$this->functionAnalyzer = new FunctionsAnalyzer();
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 4; $index > 0; --$index) {
$lambdaUseIndex = $this->getLambdaUseIndex($tokens, $index);
if (false !== $lambdaUseIndex) {
$this->fixLambda($tokens, $lambdaUseIndex);
}
}
}
private function fixLambda(Tokens $tokens, int $lambdaUseIndex): void
{
$lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($lambdaUseIndex, ['(']);
$lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex);
$imports = $this->filterArguments($tokens, $arguments);
if (0 === \count($imports)) {
return; // no imports to remove
}
$notUsedImports = $this->findNotUsedLambdaImports($tokens, $imports, $lambdaUseCloseBraceIndex);
$notUsedImportsCount = \count($notUsedImports);
if (0 === $notUsedImportsCount) {
return; // no not used imports found
}
if ($notUsedImportsCount === \count($arguments)) {
$this->clearImportsAndUse($tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex); // all imports are not used
return;
}
$this->clearImports($tokens, array_reverse($notUsedImports));
}
/**
* @return array<string, int>
*/
private function findNotUsedLambdaImports(Tokens $tokens, array $imports, int $lambdaUseCloseBraceIndex): array
{
static $riskyKinds = [
CT::T_DYNAMIC_VAR_BRACE_OPEN,
T_EVAL,
T_INCLUDE,
T_INCLUDE_ONCE,
T_REQUIRE,
T_REQUIRE_ONCE,
];
// figure out where the lambda starts ...
$lambdaOpenIndex = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']);
$curlyBracesLevel = 0;
for ($index = $lambdaOpenIndex;; ++$index) { // go through the body of the lambda and keep count of the (possible) usages of the imported variables
$token = $tokens[$index];
if ($token->equals('{')) {
++$curlyBracesLevel;
continue;
}
if ($token->equals('}')) {
--$curlyBracesLevel;
if (0 === $curlyBracesLevel) {
break;
}
continue;
}
if ($token->isGivenKind(T_STRING) && 'compact' === strtolower($token->getContent()) && $this->functionAnalyzer->isGlobalFunctionCall($tokens, $index)) {
return []; // wouldn't touch it with a ten-foot pole
}
if ($token->isGivenKind($riskyKinds)) {
return [];
}
if ($token->equals('$')) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind(T_VARIABLE)) {
return []; // "$$a" case
}
}
if ($token->isGivenKind(T_VARIABLE)) {
$content = $token->getContent();
if (isset($imports[$content])) {
unset($imports[$content]);
if (0 === \count($imports)) {
return $imports;
}
}
}
if ($token->isGivenKind(T_STRING_VARNAME)) {
$content = '$'.$token->getContent();
if (isset($imports[$content])) {
unset($imports[$content]);
if (0 === \count($imports)) {
return $imports;
}
}
}
if ($token->isClassy()) { // is anonymous class
// check if used as argument in the constructor of the anonymous class
$index = $tokens->getNextTokenOfKind($index, ['(', '{']);
if ($tokens[$index]->equals('(')) {
$closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $index, $closeBraceIndex);
$imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments);
$index = $tokens->getNextTokenOfKind($closeBraceIndex, ['{']);
}
// skip body
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if ($token->isGivenKind(T_FUNCTION)) {
// check if used as argument
$lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']);
$lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex);
$imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments);
// check if used as import
$index = $tokens->getNextTokenOfKind($index, [[CT::T_USE_LAMBDA], '{']);
if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) {
$lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']);
$lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex);
$arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex);
$imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments);
$index = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']);
}
// skip body
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
}
return $imports;
}
private function countImportsUsedAsArgument(Tokens $tokens, array $imports, array $arguments): array
{
foreach ($arguments as $start => $end) {
$info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end);
$content = $info->getName();
if (isset($imports[$content])) {
unset($imports[$content]);
if (0 === \count($imports)) {
return $imports;
}
}
}
return $imports;
}
/**
* @return false|int
*/
private function getLambdaUseIndex(Tokens $tokens, int $index)
{
if (!$tokens[$index]->isGivenKind(T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) {
return false;
}
$lambdaUseIndex = $tokens->getNextMeaningfulToken($index); // we are @ '(' or '&' after this
if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) {
$lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex);
}
$lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseIndex); // we are @ ')' after this
$lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex);
if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) {
return false;
}
return $lambdaUseIndex;
}
private function filterArguments(Tokens $tokens, array $arguments): array
{
$imports = [];
foreach ($arguments as $start => $end) {
$info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end);
$argument = $info->getNameIndex();
if ($tokens[$tokens->getPrevMeaningfulToken($argument)]->equals('&')) {
continue;
}
$argumentCandidate = $tokens[$argument];
if ('$this' === $argumentCandidate->getContent()) {
continue;
}
if ($this->tokensAnalyzer->isSuperGlobal($argument)) {
continue;
}
$imports[$argumentCandidate->getContent()] = $argument;
}
return $imports;
}
/**
* @param array<string, int> $imports
*/
private function clearImports(Tokens $tokens, array $imports): void
{
foreach ($imports as $removeIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex);
$previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex);
if ($tokens[$previousRemoveIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex);
} elseif ($tokens[$previousRemoveIndex]->equals('(')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex)); // next is always ',' here
}
}
}
/**
* Remove `use` and all imported variables.
*/
private function clearImportsAndUse(Tokens $tokens, int $lambdaUseIndex, int $lambdaUseCloseBraceIndex): void
{
for ($i = $lambdaUseCloseBraceIndex; $i >= $lambdaUseIndex; --$i) {
if ($tokens[$i]->isComment()) {
continue;
}
if ($tokens[$i]->isWhitespace()) {
$previousIndex = $tokens->getPrevNonWhitespace($i);
if ($tokens[$previousIndex]->isComment()) {
continue;
}
}
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
}
}