forked from rectorphp/rector-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveUnusedVariableAssignRector.php
More file actions
370 lines (308 loc) · 10.8 KB
/
RemoveUnusedVariableAssignRector.php
File metadata and controls
370 lines (308 loc) · 10.8 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php
declare(strict_types=1);
namespace Rector\DeadCode\Rector\Assign;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\Cast;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Include_;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\NullsafeMethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Function_;
use PhpParser\NodeVisitor;
use PHPStan\Reflection\AttributeReflection;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ObjectType;
use Rector\DeadCode\SideEffect\SideEffectNodeDetector;
use Rector\NodeAnalyzer\VariableAnalyzer;
use Rector\NodeManipulator\StmtsManipulator;
use Rector\Php\ReservedKeywordAnalyzer;
use Rector\PhpParser\Enum\NodeGroup;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\PHPStan\ScopeFetcher;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\MethodName;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector\RemoveUnusedVariableAssignRectorTest
*/
final class RemoveUnusedVariableAssignRector extends AbstractRector
{
public function __construct(
private readonly ReservedKeywordAnalyzer $reservedKeywordAnalyzer,
private readonly SideEffectNodeDetector $sideEffectNodeDetector,
private readonly VariableAnalyzer $variableAnalyzer,
private readonly BetterNodeFinder $betterNodeFinder,
private readonly StmtsManipulator $stmtsManipulator,
private readonly ReflectionProvider $reflectionProvider,
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Remove unused assigns to variables', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run()
{
$value = 5;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run()
{
}
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class, Function_::class];
}
/**
* @param ClassMethod|Function_ $node
*/
public function refactor(Node $node): null|ClassMethod|Function_
{
$stmts = $node->stmts;
if ($stmts === null || $stmts === []) {
return null;
}
// we cannot be sure here
if ($this->shouldSkip($stmts)) {
return null;
}
$assignedVariableNamesByStmtPosition = $this->resolvedAssignedVariablesByStmtPosition($stmts);
$hasChanged = false;
foreach ($assignedVariableNamesByStmtPosition as $stmtPosition => $variableName) {
if ($this->stmtsManipulator->isVariableUsedInNextStmt($node, $stmtPosition + 1, $variableName)) {
continue;
}
/** @var Expression<Assign> $currentStmt */
$currentStmt = $stmts[$stmtPosition];
/** @var Assign $assign */
$assign = $currentStmt->expr;
if ($this->isObjectWithDestructMethod($assign->expr)) {
continue;
}
if ($this->hasCallLikeInAssignExpr($assign)) {
// clean safely
$cleanAssignedExpr = $this->cleanCastedExpr($assign->expr);
$newExpression = new Expression($cleanAssignedExpr);
$this->mirrorComments($newExpression, $currentStmt);
$node->stmts[$stmtPosition] = $newExpression;
} else {
unset($node->stmts[$stmtPosition]);
}
$hasChanged = true;
}
if ($hasChanged) {
return $node;
}
return null;
}
private function isObjectWithDestructMethod(Expr $expr): bool
{
$exprType = $this->getType($expr);
if (! $exprType instanceof ObjectType) {
return false;
}
$classReflection = $exprType->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return false;
}
return $classReflection->hasNativeMethod(MethodName::DESTRUCT);
}
private function cleanCastedExpr(Expr $expr): Expr
{
if (! $expr instanceof Cast) {
return $expr;
}
return $this->cleanCastedExpr($expr->expr);
}
private function hasCallLikeInAssignExpr(Expr $expr): bool
{
return (bool) $this->betterNodeFinder->findFirst($expr, $this->sideEffectNodeDetector->detectCallExpr(...));
}
/**
* @param Stmt[] $stmts
*/
private function shouldSkip(array $stmts): bool
{
return (bool) $this->betterNodeFinder->findFirst($stmts, function (Node $node): bool {
if ($node instanceof Include_) {
return true;
}
if (! $node instanceof FuncCall) {
return false;
}
return $this->isNames($node, ['compact', 'get_defined_vars']);
});
}
/**
* @param string[] $refVariableNames
*/
private function collectAssignRefVariableNames(Stmt $stmt, array &$refVariableNames): void
{
if (! NodeGroup::isStmtAwareNode($stmt)) {
return;
}
$this->traverseNodesWithCallable($stmt, function (Node $subNode) use (&$refVariableNames): Node {
if ($subNode instanceof AssignRef && $subNode->var instanceof Variable) {
$refVariableNames[] = (string) $this->getName($subNode->var);
}
return $subNode;
});
}
/**
* @param array<int, Stmt> $stmts
* @return array<int, string>
*/
private function resolvedAssignedVariablesByStmtPosition(array $stmts): array
{
$assignedVariableNamesByStmtPosition = [];
$refVariableNames = [];
foreach ($stmts as $key => $stmt) {
if (! $stmt instanceof Expression) {
$this->collectAssignRefVariableNames($stmt, $refVariableNames);
continue;
}
if ($stmt->expr instanceof AssignRef && $stmt->expr->var instanceof Variable) {
$refVariableNames[] = (string) $this->getName($stmt->expr->var);
}
if (! $stmt->expr instanceof Assign) {
continue;
}
$this->traverseNodesWithCallable(
$stmt->expr->expr,
function (Node $subNode) use (&$refVariableNames) {
if ($subNode instanceof Class_ || $subNode instanceof Function_) {
return NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN;
}
if (! $subNode instanceof Closure) {
return null;
}
foreach ($subNode->uses as $closureUse) {
if (! $closureUse->var instanceof Variable) {
continue;
}
if (! $closureUse->byRef) {
continue;
}
$refVariableNames[] = (string) $this->getName($closureUse->var);
}
}
);
$assign = $stmt->expr;
if (! $assign->var instanceof Variable) {
continue;
}
$variableName = $this->getName($assign->var);
if (! is_string($variableName)) {
continue;
}
if ($this->reservedKeywordAnalyzer->isNativeVariable($variableName)) {
continue;
}
if ($this->shouldSkipVariable($assign->var, $variableName, $refVariableNames)) {
continue;
}
if ($this->isNoDiscardCall($assign->expr)) {
continue;
}
$assignedVariableNamesByStmtPosition[$key] = $variableName;
}
return $assignedVariableNamesByStmtPosition;
}
/**
* @param string[] $refVariableNames
*/
private function shouldSkipVariable(Variable $variable, string $variableName, array $refVariableNames): bool
{
if ($this->variableAnalyzer->isStaticOrGlobal($variable)) {
return true;
}
if ($this->variableAnalyzer->isUsedByReference($variable)) {
return true;
}
return in_array($variableName, $refVariableNames, true);
}
private function isNoDiscardCall(Expr $expr): bool
{
if ($expr instanceof FuncCall) {
$name = $this->getName($expr);
if ($name === null) {
return false;
}
$scope = ScopeFetcher::fetch($expr);
if (! $this->reflectionProvider->hasFunction(new Name($name), $scope)) {
return false;
}
return $this->hasNoDiscardAttribute(
$this->reflectionProvider->getFunction(new Name($name), $scope)
->getAttributes()
);
}
if ($expr instanceof StaticCall) {
$classNames = $this->getType($expr->class)
->getObjectClassNames();
$methodName = $this->getName($expr->name);
} elseif ($expr instanceof MethodCall || $expr instanceof NullsafeMethodCall) {
$classNames = $this->getType($expr->var)
->getObjectClassNames();
$methodName = $this->getName($expr->name);
} else {
return false;
}
if ($classNames === [] || $methodName === null) {
return false;
}
foreach ($classNames as $className) {
if (! $this->reflectionProvider->hasClass($className)) {
continue;
}
$classReflection = $this->reflectionProvider->getClass($className);
if (! $classReflection->hasNativeMethod($methodName)) {
continue;
}
if ($this->hasNoDiscardAttribute($classReflection->getNativeMethod($methodName)->getAttributes())) {
return true;
}
}
return false;
}
/**
* @param AttributeReflection[] $attributes
*/
private function hasNoDiscardAttribute(array $attributes): bool
{
foreach ($attributes as $attribute) {
if ($attribute->getName() === 'NoDiscard') {
return true;
}
}
return false;
}
}