Skip to content

Commit

Permalink
[SOLID] Review Changes
Browse files Browse the repository at this point in the history
  • Loading branch information
dobryy committed Oct 9, 2020
1 parent d2692f2 commit 38047f4
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 10 deletions.
28 changes: 18 additions & 10 deletions rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Rector\SOLID\Rector\If_;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Stmt;
Expand Down Expand Up @@ -112,24 +113,22 @@ public function refactor(Node $node): ?Node

/** @var BooleanAnd $expr */
$expr = $node->cond;
$invertedLeftCondition = $this->conditionInverter->createInvertedCondition($expr->left);
$invertedRightCondition = $this->conditionInverter->createInvertedCondition($expr->right);
$firstIf = $this->createInvertedIfConditionNodeFromExpr($expr->left);
$secondIf = $this->createInvertedIfConditionNodeFromExpr($expr->right);

$firstIf = new If_($invertedLeftCondition);
$firstIf->stmts = [new Return_()];
$secondIf = new If_($invertedRightCondition);
$secondIf->stmts = [new Return_()];
$nodeComments = $node->getAttribute(AttributeKey::COMMENTS);
$firstIf->setAttribute(AttributeKey::COMMENTS, $nodeComments);

$this->addNodesAfterNode([$firstIf, $secondIf, $ifReturn], $node);

$this->addNodeAfterNode($firstIf, $node);
$this->addNodeAfterNode($secondIf, $node);
$this->addNodeAfterNode($ifReturn, $node);
$this->removeNode($node);

$functionLikeReturn = $this->getFunctionLikeReturn($node);
if ($functionLikeReturn !== null) {
$this->removeNode($functionLikeReturn);
}

$this->removeNode($node);

return null;
}

Expand Down Expand Up @@ -224,4 +223,13 @@ private function isLastIfOrBeforeLastReturn(If_ $if): bool
}
return $nextNode instanceof Return_;
}

private function createInvertedIfConditionNodeFromExpr(Expr $expr): If_
{
$invertedCondition = $this->conditionInverter->createInvertedCondition($expr);
$if = new If_($invertedCondition);
$if->stmts = [new Return_()];

return $if;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Rector\SOLID\Tests\Rector\If_\ChangeAndIfToEarlyReturnRector\Fixture;

class KeepCommentOfRemovedNodeClass
{
public function canDrive(Car $car): void
{
// keep this comment
if ($car->hasWheels && $car->hasFuel) {
$this->canDrive = true;
}

return;
}
}

?>
-----
<?php

namespace Rector\SOLID\Tests\Rector\If_\ChangeAndIfToEarlyReturnRector\Fixture;

class KeepCommentOfRemovedNodeClass
{
public function canDrive(Car $car): void
{
// keep this comment
if (!$car->hasWheels) {
return;
}
if (!$car->hasFuel) {
return;
}
$this->canDrive = true;
}
}

?>

0 comments on commit 38047f4

Please sign in to comment.