Skip to content

Commit

Permalink
[DeadCode] Skip nullable array on RemoveUnusedNonEmptyArrayBeforeFore…
Browse files Browse the repository at this point in the history
…achRector (#5375)

* [DeadCode] Skip nullable array on RemoveUnusedNonEmptyArrayBeforeForeachRector

* updaet

* Fixed 🎉

* comment for future reference
  • Loading branch information
samsonasik committed Dec 21, 2023
1 parent 4283bef commit 7ca4de0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
@@ -0,0 +1,19 @@
<?php

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

class SkipNullableArray
{
public function run(?array $values) {
if (empty($values)) {
return;
}

foreach ($values as $value) {
echo $value;
}
}
}

?>

Expand Up @@ -8,6 +8,7 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\Empty_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Foreach_;
Expand Down Expand Up @@ -177,6 +178,19 @@ private function refactorStmtsAware(StmtsAwareInterface $stmtsAware): ?StmtsAwar
continue;
}

/** @var Empty_ $empty */
$empty = $previousStmt->cond;
// scope need to be pulled from Empty_ node to ensure it get correct type
$scope = $empty->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
continue;
}

$ifType = $scope->getNativeType($empty->expr);
if (! $ifType->isArray()->yes()) {
continue;
}

unset($stmtsAware->stmts[$key - 1]);
return $stmtsAware;
}
Expand Down

0 comments on commit 7ca4de0

Please sign in to comment.