Skip to content

Commit

Permalink
[EarlyReturn] Move comment in If_ stmt for ChangeAndIfToEarlyReturnRe…
Browse files Browse the repository at this point in the history
…ctor (#648)
  • Loading branch information
samsonasik committed Aug 11, 2021
1 parent 90fd207 commit e35724e
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

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

class MoveCommentInIfStmt
{
public function canDrive(Car $car)
{
if ($car->hasWheels && $car->hasFuel) {
// a comment
return true;
}

return false;
}
}

?>
-----
<?php

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

class MoveCommentInIfStmt
{
public function canDrive(Car $car)
{
if (!$car->hasWheels) {
return false;
}
if (!$car->hasFuel) {
return false;
}
// a comment
return true;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

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

class MoveCommentInIfStmt2
{
public function canDrive(Car $car)
{
if ($car->hasWheels && $car->hasFuel) {
// a comment
return true;
}

// another comment
return false;
}
}

?>
-----
<?php

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

class MoveCommentInIfStmt2
{
public function canDrive(Car $car)
{
if (!$car->hasWheels) {
// another comment
return false;
}
if (!$car->hasFuel) {
// another comment
return false;
}
// a comment
return true;
}
}

?>
7 changes: 6 additions & 1 deletion rules/EarlyReturn/NodeFactory/InvertedIfFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,15 @@ public function __construct(
public function createFromConditions(If_ $if, array $conditions, Return_ $return): array
{
$ifs = [];
$stmt = $this->contextAnalyzer->isInLoop($if) && ! $this->getIfNextReturn($if)
$ifNextReturn = $this->getIfNextReturn($if);
$stmt = $this->contextAnalyzer->isInLoop($if) && ! $ifNextReturn
? [new Continue_()]
: [$return];

if ($ifNextReturn instanceof Return_) {
$stmt[0]->setAttribute(AttributeKey::COMMENTS, $ifNextReturn->getAttribute(AttributeKey::COMMENTS));
}

$getNextReturnExpr = $this->getNextReturnExpr($if);
if ($getNextReturnExpr instanceof Return_) {
$return->expr = $getNextReturnExpr->expr;
Expand Down

0 comments on commit e35724e

Please sign in to comment.