Skip to content

Commit

Permalink
[SOLID] Change if && to early return (#4344)
Browse files Browse the repository at this point in the history
Co-authored-by: rector-bot <tomas@getrector.org>
  • Loading branch information
dobryy and rector-bot committed Oct 10, 2020
1 parent 0cbf0e5 commit 35537db
Show file tree
Hide file tree
Showing 24 changed files with 741 additions and 23 deletions.
3 changes: 3 additions & 0 deletions config/set/solid.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Rector\SOLID\Rector\Class_\MakeUnusedClassesWithChildrenAbstractRector;
use Rector\SOLID\Rector\Class_\RepeatedLiteralToClassConstantRector;
use Rector\SOLID\Rector\Foreach_\ChangeNestedForeachIfsToEarlyContinueRector;
use Rector\SOLID\Rector\If_\ChangeAndIfToEarlyReturnRector;
use Rector\SOLID\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector;
use Rector\SOLID\Rector\If_\ChangeNestedIfsToEarlyReturnRector;
use Rector\SOLID\Rector\If_\RemoveAlwaysElseRector;
Expand Down Expand Up @@ -39,4 +40,6 @@
$services->set(ChangeIfElseValueAssignToEarlyReturnRector::class);

$services->set(UseMessageVariableForSprintfInSymfonyStyleRector::class);

$services->set(ChangeAndIfToEarlyReturnRector::class);
};
32 changes: 31 additions & 1 deletion docs/rector_rules_overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
- [RemovingStatic](#removingstatic) (6)
- [Renaming](#renaming) (10)
- [Restoration](#restoration) (8)
- [SOLID](#solid) (12)
- [SOLID](#solid) (13)
- [Sensio](#sensio) (3)
- [StrictCodeQuality](#strictcodequality) (1)
- [Symfony](#symfony) (34)
Expand Down Expand Up @@ -13926,6 +13926,36 @@ Add false default to bool properties, to prevent null compare errors

<br><br>

### `ChangeAndIfToEarlyReturnRector`

- class: [`Rector\SOLID\Rector\If_\ChangeAndIfToEarlyReturnRector`](/rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php)
- [test fixtures](/rules/solid/tests/Rector/If_/ChangeAndIfToEarlyReturnRector/Fixture)

Changes if && to early return

```diff
class SomeClass
{
public function canDrive(Car $car)
{
- if ($car->hasWheels && $car->hasFuel) {
- return true;
+ if (!$car->hasWheels) {
+ return false;
}

- return false;
+ if (!$car->hasFuel) {
+ return false;
+ }
+
+ return true;
}
}
```

<br><br>

### `ChangeIfElseValueAssignToEarlyReturnRector`

- class: [`Rector\SOLID\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector`](/rules/solid/src/Rector/If_/ChangeIfElseValueAssignToEarlyReturnRector.php)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,13 @@ private function renameClass(string $lastName, Class_ $class, Node $usedNameNode
*/
private function renameParam(string $lastName, Node $parentNode, Node $usedNameNode): void
{
if ($parentNode->type !== null && $this->areNamesEqual($parentNode->type, $usedNameNode)) {
$parentNode->type = new Name($lastName);
if ($parentNode->type === null) {
return;
}
if (! $this->areNamesEqual($parentNode->type, $usedNameNode)) {
return;
}
$parentNode->type = new Name($lastName);
}

/**
Expand Down
9 changes: 6 additions & 3 deletions rules/nette/src/TemplatePropertyAssignCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,14 @@ private function collectVariableFromAssign(Assign $assign): void

$this->nodesToRemove[] = $assign;
}

// $x = $this->template
if ($assign->var instanceof Variable && $this->isTemplatePropertyFetch($assign->expr)) {
$this->nodesToRemove[] = $assign;
if (! $assign->var instanceof Variable) {
return;
}
if (! $this->isTemplatePropertyFetch($assign->expr)) {
return;
}
$this->nodesToRemove[] = $assign;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,13 @@ private function renameMethod(
)) {
$methodCall->name = new Identifier($functionNameWithAssertMethods->getAssetMethodName());
}

if ($functionNameWithAssertMethods->getNotAssertMethodName() && in_array(
$oldMethodName,
['assertFalse', 'assertNotTrue'],
true
)) {
$methodCall->name = new Identifier($functionNameWithAssertMethods->getNotAssertMethodName());
if ($functionNameWithAssertMethods->getNotAssertMethodName() === '') {
return;
}
if (! in_array($oldMethodName, ['assertFalse', 'assertNotTrue'], true)) {
return;
}
$methodCall->name = new Identifier($functionNameWithAssertMethods->getNotAssertMethodName());
}

/**
Expand Down
4 changes: 4 additions & 0 deletions rules/solid/src/NodeTransformer/ConditionInverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ public function createInvertedCondition(Expr $expr): Expr
return $inversedCondition;
}

if ($expr instanceof BooleanNot) {
return $expr->expr;
}

return new BooleanNot($expr);
}
}
234 changes: 234 additions & 0 deletions rules/solid/src/Rector/If_/ChangeAndIfToEarlyReturnRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
<?php

declare(strict_types=1);

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;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\PhpParser\Node\Manipulator\IfManipulator;
use Rector\Core\PhpParser\Node\Manipulator\StmtsManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\SOLID\NodeTransformer\ConditionInverter;

/**
* @see \Rector\SOLID\Tests\Rector\If_\ChangeAndIfToEarlyReturnRector\ChangeAndIfToEarlyReturnRectorTest
*/
final class ChangeAndIfToEarlyReturnRector extends AbstractRector
{
/**
* @var IfManipulator
*/
private $ifManipulator;

/**
* @var ConditionInverter
*/
private $conditionInverter;

/**
* @var StmtsManipulator
*/
private $stmtsManipulator;

public function __construct(
ConditionInverter $conditionInverter,
IfManipulator $ifManipulator,
StmtsManipulator $stmtsManipulator
) {
$this->ifManipulator = $ifManipulator;
$this->conditionInverter = $conditionInverter;
$this->stmtsManipulator = $stmtsManipulator;
}

public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Changes if && to early return', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function canDrive(Car $car)
{
if ($car->hasWheels && $car->hasFuel) {
return true;
}
return false;
}
}
CODE_SAMPLE

,
<<<'CODE_SAMPLE'
class SomeClass
{
public function canDrive(Car $car)
{
if (!$car->hasWheels) {
return false;
}
if (!$car->hasFuel) {
return false;
}
return true;
}
}
CODE_SAMPLE
),
]);
}

/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [If_::class];
}

/**
* @param If_ $node
*/
public function refactor(Node $node): ?Node
{
if ($this->shouldSkip($node)) {
return null;
}

$ifReturn = $this->getIfReturn($node);
if ($ifReturn === null) {
return null;
}

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

$nodeComments = $node->getAttribute(AttributeKey::COMMENTS);
$firstIf->setAttribute(AttributeKey::COMMENTS, $nodeComments);

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

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

$this->removeNode($node);

return null;
}

private function shouldSkip(If_ $if): bool
{
if (! $this->ifManipulator->isIfWithOnlyOneStmt($if)) {
return true;
}

if (! $this->ifManipulator->isIfFirstLevelStmt($if)) {
return true;
}

if (! $if->cond instanceof BooleanAnd) {
return true;
}

if ($this->hasMoreThanTwoConditions($if)) {
return true;
}

if (! $this->isFunctionLikeReturnsVoid($if)) {
return true;
}

if ($if->else !== null) {
return true;
}

if ($if->elseifs !== []) {
return true;
}

return ! $this->isLastIfOrBeforeLastReturn($if);
}

private function getIfReturn(If_ $if): ?Stmt
{
$ifStmt = end($if->stmts);
if ($ifStmt === false) {
return null;
}

return $ifStmt;
}

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

return $if;
}

private function getFunctionLikeReturn(If_ $if): ?Return_
{
/** @var FunctionLike|null $functionLike */
$functionLike = $this->betterNodeFinder->findFirstParentInstanceOf($if, FunctionLike::class);
if ($functionLike === null) {
return null;
}

if ($functionLike->getStmts() === null) {
return null;
}

$return = $this->stmtsManipulator->getUnwrappedLastStmt($functionLike->getStmts());
if ($return === null) {
return null;
}

if (! $return instanceof Return_) {
return null;
}

return $return;
}

private function hasMoreThanTwoConditions(If_ $if): bool
{
$binaryOps = $this->betterNodeFinder->findInstanceOf($if->cond, BooleanAnd::class);
return count($binaryOps) >= 2;
}

private function isFunctionLikeReturnsVoid(If_ $if): bool
{
$return = $this->getFunctionLikeReturn($if);
if ($return === null) {
return true;
}

return $return->expr === null;
}

private function isLastIfOrBeforeLastReturn(If_ $if): bool
{
$nextNode = $if->getAttribute(AttributeKey::NEXT_NODE);
if ($nextNode === null) {
return true;
}
return $nextNode instanceof Return_;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

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

use Iterator;
use Rector\Core\Testing\PHPUnit\AbstractRectorTestCase;
use Rector\SOLID\Rector\If_\ChangeAndIfToEarlyReturnRector;
use Symplify\SmartFileSystem\SmartFileInfo;

final class ChangeAndIfToEarlyReturnRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}

public function provideData(): Iterator
{
return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

protected function getRectorClass(): string
{
return ChangeAndIfToEarlyReturnRector::class;
}
}

0 comments on commit 35537db

Please sign in to comment.