[EarlyReturn] Skip same return expr on ChangeOrIfReturnToEarlyReturnRector (#797)

* [EarlyReturn] Skip same return expr on ChangeOrIfReturnToEarlyReturnRector

* fixture update

* phpstan

* rollback handling tweak on NarrowUnionTypeDocRector

* tweak
This commit is contained in:
Abdul Malik Ikhsan 2021-08-31 19:51:46 +07:00 committed by GitHub
parent 654d4a2a2b
commit 4d60c23f7c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 11 deletions

View File

@ -0,0 +1,16 @@
<?php
namespace Rector\Tests\EarlyReturn\Rector\If_\ChangeOrIfReturnToEarlyReturnRector\Fixture;
class SkipSameReturn
{
public function run($a, $b, $c)
{
if ($a && $b || $c) {
return null;
}
return null;
}
}
?>

View File

@ -90,14 +90,11 @@ CODE_SAMPLE
}
}
if (! $phpDocInfo->hasChanged()) {
return null;
if ($phpDocInfo->hasChanged()) {
$node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true);
return $node;
}
$node->setAttribute(AttributeKey::HAS_PHP_DOC_INFO_JUST_CHANGED, true);
// @see https://github.com/rectorphp/rector-src/pull/795
// avoid duplicated ifs and returns when combined with ChangeOrIfReturnToEarlyReturnRector, ChangeAndIfToEarlyReturnRector, and AddArrayReturnDocTypeRector
return null;
}

View File

@ -91,16 +91,18 @@ CODE_SAMPLE
}
$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
if ($nextNode === null) {
return null;
}
if ($nextNode instanceof Return_ && $nextNode->expr === null) {
if ($this->shouldSkip($nextNode)) {
return null;
}
/** @var Return_ $return */
$return = $node->stmts[0];
// avoid repetitive ifs combined with other rules
if ($nextNode instanceof Return_ && $this->nodeComparator->areNodesEqual($nextNode->expr, $return->expr)) {
return null;
}
$ifs = $this->createMultipleIfs($node->cond, $return, []);
foreach ($ifs as $key => $if) {
@ -115,6 +117,15 @@ CODE_SAMPLE
return $node;
}
private function shouldSkip(?Node $nextNode): bool
{
if ($nextNode === null) {
return true;
}
return $nextNode instanceof Return_ && $nextNode->expr === null;
}
/**
* @param If_[] $ifs
* @return If_[]