diff --git a/rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php b/rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php index 75d3d846bef..91f8b77ca65 100644 --- a/rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php +++ b/rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php @@ -122,9 +122,9 @@ CODE_SAMPLE $this->addNodesAfterNode($ifs, $node); $this->addNodeAfterNode($ifReturn, $node); - $ifParentReturn = $this->getIfParentReturn($node); - if ($ifParentReturn !== null) { - $this->removeNode($ifParentReturn); + $ifNextReturn = $this->getIfNextReturn($node); + if ($ifNextReturn !== null && !$this->isIfInLoop($node)) { + $this->removeNode($ifNextReturn); } $this->removeNode($node); @@ -221,7 +221,7 @@ CODE_SAMPLE $ifs[0]->setAttribute(AttributeKey::COMMENTS, $nodeComments); } - private function getIfParentReturn(If_ $if): ?Return_ + private function getIfNextReturn(If_ $if): ?Return_ { $nextNode = $if->getAttribute(AttributeKey::NEXT_NODE); if (! $nextNode instanceof Return_) { @@ -279,4 +279,11 @@ CODE_SAMPLE } return $nextNode instanceof Return_; } + + private function isIfInLoop(If_ $if): bool + { + $parentLoop = $this->betterNodeFinder->findFirstParentInstanceOf($if, [Stmt\Foreach_::class, Stmt\For_::class, Stmt\While_::class]); + + return $parentLoop !== null; + } } diff --git a/rules/solid/tests/Rector/If_/ChangeAndIfToEarlyReturnRector/Fixture/if_in_foreach.php.inc b/rules/solid/tests/Rector/If_/ChangeAndIfToEarlyReturnRector/Fixture/if_in_foreach.php.inc index 4ceea52a975..819e37af8e6 100644 --- a/rules/solid/tests/Rector/If_/ChangeAndIfToEarlyReturnRector/Fixture/if_in_foreach.php.inc +++ b/rules/solid/tests/Rector/If_/ChangeAndIfToEarlyReturnRector/Fixture/if_in_foreach.php.inc @@ -42,6 +42,7 @@ class IfInForeachClass return; } $this->processNameOrIdentifier($node); + return; } return;