Skip to content

Commit

Permalink
[DeadCode] Skip assign closure bind by reference on RemoveUnusedVaria…
Browse files Browse the repository at this point in the history
…bleAssignRector (#3942)

* [DeadCode] Skip assign closure bind by reference on RemoveUnusedVariableAssignRector

* Fixed 🎉
  • Loading branch information
samsonasik committed May 24, 2023
1 parent a354eda commit 62ecc90
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector\Fixture;

final class SkipAssignClosureBindReference
{
public function run(object $container)
{
$containerLocked = &Closure::bind(static fn &($container) => $container->locked, null, $container)($container);
$containerLocked = false;
}
}
28 changes: 23 additions & 5 deletions rules/DeadCode/Rector/Assign/RemoveUnusedVariableAssignRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
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\FuncCall;
use PhpParser\Node\Expr\Include_;
Expand Down Expand Up @@ -195,12 +196,17 @@ private function containsFileIncludes(ClassMethod $classMethod): bool
private function resolvedAssignedVariablesByStmtPosition(array $stmts): array
{
$assignedVariableNamesByStmtPosition = [];
$refVariableNames = [];

foreach ($stmts as $key => $stmt) {
if (! $stmt instanceof Expression) {
continue;
}

if ($stmt->expr instanceof AssignRef && $stmt->expr->var instanceof Variable) {
$refVariableNames[] = (string) $this->getName($stmt->expr->var);
}

if (! $stmt->expr instanceof Assign) {
continue;
}
Expand All @@ -219,11 +225,7 @@ private function resolvedAssignedVariablesByStmtPosition(array $stmts): array
continue;
}

if ($this->variableAnalyzer->isStaticOrGlobal($assign->var)) {
continue;
}

if ($this->variableAnalyzer->isUsedByReference($assign->var)) {
if ($this->shouldSkipVariable($assign->var, $variableName, $refVariableNames)) {
continue;
}

Expand All @@ -232,4 +234,20 @@ private function resolvedAssignedVariablesByStmtPosition(array $stmts): array

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);
}
}

0 comments on commit 62ecc90

Please sign in to comment.