diff --git a/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php b/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php index f0aa4f0ff40..8320de3165e 100644 --- a/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php +++ b/rules/DeadCode/Rector/If_/RemoveUnusedNonEmptyArrayBeforeForeachRector.php @@ -105,7 +105,7 @@ public function refactorWithScope(Node $node, Scope $scope): array|Node|null return $stmt; } - return $this->refactorStmtsAware($node); + return $this->refactorStmtsAware($node, false); } private function isUselessBeforeForeachCheck(If_ $if, Scope $scope): bool @@ -162,20 +162,27 @@ private function isUselessBooleanAnd(BooleanAnd $booleanAnd, Expr $foreachExpr): return $this->countManipulator->isCounterHigherThanOne($booleanAnd->right, $foreachExpr); } - private function refactorStmtsAware(StmtsAwareInterface $stmtsAware): ?StmtsAwareInterface + private function refactorStmtsAware(StmtsAwareInterface $node, bool $hasChanged, int $jumpToKey = 0): ?StmtsAwareInterface { - foreach ((array) $stmtsAware->stmts as $key => $stmt) { - if (! $stmt instanceof If_) { - continue; + if ($node->stmts === null) { + return null; + } + + $totalKeys = array_key_last($node->stmts); + for ($key = $jumpToKey; $key < $totalKeys; ++$key) { + if (! isset($node->stmts[$key], $node->stmts[$key + 1])) { + break; } - $nextStmt = $stmtsAware->stmts[$key + 1] ?? null; - if (! $nextStmt instanceof Foreach_) { + $stmt = $node->stmts[$key]; + $nextStmt = $node->stmts[$key + 1]; + + if (! $stmt instanceof If_) { continue; } - // the foreach must be the last one - if (isset($stmtsAware->stmts[$key + 2])) { + $nextStmt = $node->stmts[$key + 1] ?? null; + if (! $nextStmt instanceof Foreach_) { continue; } @@ -186,8 +193,15 @@ private function refactorStmtsAware(StmtsAwareInterface $stmtsAware): ?StmtsAwar continue; } - unset($stmtsAware->stmts[$key]); - return $stmtsAware; + unset($node->stmts[$key]); + + $hasChanged = true; + + return $this->refactorStmtsAware($node, $hasChanged, $key + 2); + } + + if ($hasChanged) { + return $node; } return null;