Skip to content

Commit

Permalink
Add the patch by loop jump to key recursive
Browse files Browse the repository at this point in the history
  • Loading branch information
samsonasik committed Apr 13, 2023
1 parent ceb6b33 commit 9375b38
Showing 1 changed file with 25 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}

Expand All @@ -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;
Expand Down

0 comments on commit 9375b38

Please sign in to comment.