[EarlyReturn] Move comment in If_ stmt for ChangeAndIfToEarlyReturnRector (#648)

This commit is contained in:
Abdul Malik Ikhsan 2021-08-11 23:02:50 +07:00 committed by GitHub
parent 90fd207cf6
commit e35724edae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 87 additions and 1 deletions

View File

@ -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;
}
}
?>

View File

@ -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;
}
}
?>

View File

@ -30,10 +30,15 @@ final class InvertedIfFactory
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;