Skip to content

Commit 39027f6

Browse files
authored
[DeadCode] Skip used from property fetch reference on loop on RemoveUnusedVariableAssignRector (#7635)
* [DeadCode] Skip used from property fetch reference on loop on RemoveUnusedVariableAssignRector * fix phpstan
1 parent aba25a9 commit 39027f6

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace Rector\Tests\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector\Fixture;
4+
5+
function SkipUsedFromPropertyFetchReference(\stdClass $target, array $path, mixed $value): void {
6+
$current = $target;
7+
foreach ($path as $key) {
8+
$current = &$current->{$key};
9+
}
10+
$current = $value;
11+
}
12+
13+
?>

rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use PhpParser\Node\Stmt\Expression;
2020
use PhpParser\Node\Stmt\Function_;
2121
use PhpParser\NodeVisitor;
22+
use Rector\Contract\PhpParser\Node\StmtsAwareInterface;
2223
use Rector\DeadCode\SideEffect\SideEffectNodeDetector;
2324
use Rector\NodeAnalyzer\VariableAnalyzer;
2425
use Rector\NodeManipulator\StmtsManipulator;
@@ -158,6 +159,27 @@ private function shouldSkip(array $stmts): bool
158159
});
159160
}
160161

162+
/**
163+
* @param string[] $refVariableNames
164+
*/
165+
private function collectAssignRefVariableNames(Stmt $stmt, array &$refVariableNames): void
166+
{
167+
if (! $stmt instanceof StmtsAwareInterface) {
168+
return;
169+
}
170+
171+
$this->traverseNodesWithCallable(
172+
$stmt,
173+
function (Node $subNode) use (&$refVariableNames): Node {
174+
if ($subNode instanceof AssignRef && $subNode->var instanceof Variable) {
175+
$refVariableNames[] = (string) $this->getName($subNode->var);
176+
}
177+
178+
return $subNode;
179+
}
180+
);
181+
}
182+
161183
/**
162184
* @param array<int, Stmt> $stmts
163185
* @return array<int, string>
@@ -169,6 +191,7 @@ private function resolvedAssignedVariablesByStmtPosition(array $stmts): array
169191

170192
foreach ($stmts as $key => $stmt) {
171193
if (! $stmt instanceof Expression) {
194+
$this->collectAssignRefVariableNames($stmt, $refVariableNames);
172195
continue;
173196
}
174197

0 commit comments

Comments
 (0)