Skip to content

Commit

Permalink
[CodeQuality] Remove next node attribute usage on SimplifyIfNotNullRe…
Browse files Browse the repository at this point in the history
…turnRector (#3517)
  • Loading branch information
samsonasik committed Mar 25, 2023
1 parent da3eb40 commit d2459d1
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions rules/CodeQuality/Rector/If_/SimplifyIfNotNullReturnRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Stmt;
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;

Expand Down Expand Up @@ -54,33 +53,46 @@ 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): ?Stmt
public function refactor(Node $node): ?StmtsAwareInterface
{
$expr = $this->ifManipulator->matchIfNotNullReturnValue($node);
if ($expr instanceof Expr) {
$insideIfNode = $node->stmts[0];
foreach ((array) $node->stmts as $key => $stmt) {
if (! $stmt instanceof If_) {
continue;
}

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

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

$expr = $this->ifManipulator->matchIfNotNullReturnValue($stmt);
if (! $expr instanceof Expr) {
continue;
}

$insideIfNode = $stmt->stmts[0];
if (! $nextNode->expr instanceof Expr) {
return null;
continue;
}

if (! $this->valueResolver->isNull($nextNode->expr)) {
return null;
continue;
}

$this->removeNode($nextNode);
return $insideIfNode;
unset($node->stmts[$key]);
$node->stmts[$key + 1] = $insideIfNode;

return $node;
}

return null;
Expand Down

0 comments on commit d2459d1

Please sign in to comment.