Skip to content

Commit

Permalink
[CodeQuality] Remove next node attribute usage on SimplifyIfExactValu…
Browse files Browse the repository at this point in the history
…eReturnValueRector (#3511)

* [CodeQuality] Remove next node attribute usage on SimplifyIfExactValueReturnValueRector

* Fix

* clean up

* final touch: early return null on not match on return

* Final touch: clean up
  • Loading branch information
samsonasik committed Mar 23, 2023
1 parent d7e8477 commit 5d95d49
Showing 1 changed file with 30 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\Contract\PhpParser\Node\StmtsAwareInterface;
use Rector\Core\NodeManipulator\IfManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\CodeQuality\Rector\If_\SimplifyIfNullableReturnRector\SimplifyIfNullableReturnRectorTest
* @see \Rector\Tests\CodeQuality\Rector\If_\SimplifyIfExactValueReturnValueRector\SimplifyIfExactValueReturnValueRectorTest
*/
final class SimplifyIfExactValueReturnValueRector extends AbstractRector
{
Expand Down Expand Up @@ -53,29 +53,42 @@ public function getRuleDefinition(): RuleDefinition
*/
public function getNodeTypes(): array
{
return [If_::class];
return [StmtsAwareInterface::class];
}

/**
* @param If_ $node
* @param StmtsAwareInterface $node
*/
public function refactor(Node $node): ?Return_
public function refactor(Node $node): ?StmtsAwareInterface
{
$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
if (! $nextNode instanceof Return_) {
return null;
}
foreach ((array) $node->stmts as $key => $stmt) {
if (! $stmt instanceof If_) {
continue;
}

$expr = $this->ifManipulator->matchIfValueReturnValue($node);
if (! $expr instanceof Expr) {
return null;
}
// on last stmt already
if (! isset($node->stmts[$key+1])) {
return null;
}

$nextNode = $node->stmts[$key+1];
if (! $nextNode instanceof Return_) {
return null;
}

$expr = $this->ifManipulator->matchIfValueReturnValue($stmt);
if (! $expr instanceof Expr) {
return null;
}

if (! $this->nodeComparator->areNodesEqual($expr, $nextNode->expr)) {
return null;
}

if (! $this->nodeComparator->areNodesEqual($expr, $nextNode->expr)) {
return null;
unset($node->stmts[$key]);
return $node;
}

$this->removeNode($nextNode);
return clone $nextNode;
return null;
}
}

0 comments on commit 5d95d49

Please sign in to comment.