[DeadCode] Skip RemoveUnusedNonEmptyArrayBeforeForeachRector on native Variable (#748)

* [DeadCode] Skip RemoveUnusedNonEmptyArrayBeforeForeachRector on native Variable

* phpstan
This commit is contained in:
Abdul Malik Ikhsan 2021-08-24 12:19:10 +07:00 committed by GitHub
parent 9443e84512
commit 6ff80ba037
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 1 deletions

View File

@ -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;
}
}
}
}
?>

View File

@ -5,9 +5,11 @@ declare(strict_types=1);
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;
@ -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
) {
}
@ -103,6 +106,13 @@ CODE_SAMPLE
$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;
}