Skip to content

Commit

Permalink
[EarlyReturn] Refactor ChangeAndIfToEarlyReturnRector (#878)
Browse files Browse the repository at this point in the history
* [EarlyReturn] Refactor ChangeAndIfToEarlyReturnRector

* [ci-review] Rector Rectify

Co-authored-by: GitHub Action <action@github.com>
  • Loading branch information
samsonasik and actions-user committed Sep 14, 2021
1 parent 474024f commit 6f0288d
Showing 1 changed file with 12 additions and 21 deletions.
33 changes: 12 additions & 21 deletions rules/EarlyReturn/Rector/If_/ChangeAndIfToEarlyReturnRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\ElseIf_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\NodeManipulator\IfManipulator;
Expand Down Expand Up @@ -113,21 +112,16 @@ public function refactor(Node $node)
}

$this->removeNode($ifNextReturn);
$ifNextReturn = $node->stmts[0];
$this->nodesToAddCollector->addNodeAfterNode($ifNextReturn, $node);
$this->nodesToAddCollector->addNodeAfterNode($node->stmts[0], $node);

$ifNextReturnClone = $ifNextReturn instanceof Return_
? clone $ifNextReturn
$ifNextReturnClone = $node->stmts[0] instanceof Return_
? clone $node->stmts[0]
: new Return_();

if (! $this->contextAnalyzer->isInLoop($node)) {
return $this->processReplaceIfs($node, $booleanAndConditions, $ifNextReturnClone);
}

if (! $ifNextReturn instanceof Expression) {
return null;
}

$this->nodesToAddCollector->addNodeAfterNode(new Return_(), $node);
return $this->processReplaceIfs($node, $booleanAndConditions, $ifNextReturnClone);
}
Expand All @@ -136,24 +130,21 @@ public function refactor(Node $node)
* @param Expr[] $conditions
* @return If_|Node[]
*/
private function processReplaceIfs(If_ $node, array $conditions, Return_ $ifNextReturnClone): If_ | array
private function processReplaceIfs(If_ $if, array $conditions, Return_ $ifNextReturnClone): If_ | array
{
$ifs = $this->invertedIfFactory->createFromConditions($node, $conditions, $ifNextReturnClone);
$this->mirrorComments($ifs[0], $node);

foreach ($ifs as $if) {
$this->nodesToAddCollector->addNodeBeforeNode($if, $node);
}
$ifs = $this->invertedIfFactory->createFromConditions($if, $conditions, $ifNextReturnClone);
$this->mirrorComments($ifs[0], $if);

$this->removeNode($node);
$this->nodesToAddCollector->addNodesBeforeNode($ifs, $if);
$this->removeNode($if);

if (! $node->stmts[0] instanceof Return_ && $ifNextReturnClone->expr instanceof Expr && ! $this->contextAnalyzer->isInLoop(
$node
if (! $if->stmts[0] instanceof Return_ && $ifNextReturnClone->expr instanceof Expr && ! $this->contextAnalyzer->isInLoop(
$if
)) {
return [$node, $ifNextReturnClone];
return [$if, $ifNextReturnClone];
}

return $node;
return $if;
}

private function shouldSkip(If_ $if): bool
Expand Down

0 comments on commit 6f0288d

Please sign in to comment.