Skip to content

Commit

Permalink
[DeadCode] Skip RemoveUnusedNonEmptyArrayBeforeForeachRector on nativ…
Browse files Browse the repository at this point in the history
…e Variable (#748)

* [DeadCode] Skip RemoveUnusedNonEmptyArrayBeforeForeachRector on native Variable

* phpstan
  • Loading branch information
samsonasik committed Aug 24, 2021
1 parent 9443e84 commit 6ff80ba
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Rector\Tests\DeadCode\Rector\If_\RemoveUnusedNonEmptyArrayBeforeForeachRector\Fixture;

class SkipOnNativeVariable
{
public function run()
{
if (!empty($_SESSION)) {
foreach ($_SESSION as $value) {
echo $value;
}
}
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
namespace Rector\DeadCode\Rector\If_;

use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\If_;
use Rector\Core\NodeManipulator\IfManipulator;
use Rector\Core\Php\ReservedKeywordAnalyzer;
use Rector\Core\Rector\AbstractRector;
use Rector\DeadCode\NodeManipulator\CountManipulator;
use Rector\DeadCode\UselessIfCondBeforeForeachDetector;
Expand All @@ -23,7 +25,8 @@ final class RemoveUnusedNonEmptyArrayBeforeForeachRector extends AbstractRector
public function __construct(
private CountManipulator $countManipulator,
private IfManipulator $ifManipulator,
private UselessIfCondBeforeForeachDetector $uselessIfCondBeforeForeachDetector
private UselessIfCondBeforeForeachDetector $uselessIfCondBeforeForeachDetector,
private ReservedKeywordAnalyzer $reservedKeywordAnalyzer
) {
}

Expand Down Expand Up @@ -103,6 +106,13 @@ private function isUselessBeforeForeachCheck(If_ $if): bool
$foreach = $if->stmts[0];
$foreachExpr = $foreach->expr;

if ($foreachExpr instanceof Variable) {
$variableName = $this->nodeNameResolver->getName($foreachExpr);
if (is_string($variableName) && $this->reservedKeywordAnalyzer->isNativeVariable($variableName)) {
return false;
}
}

if ($this->uselessIfCondBeforeForeachDetector->isMatchingNotIdenticalEmptyArray($if, $foreachExpr)) {
return true;
}
Expand Down

0 comments on commit 6ff80ba

Please sign in to comment.