Skip to content

Commit

Permalink
Refactor from PARENT_NODE in PostIncDecToPreIncDecRector (#3962)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed May 25, 2023
1 parent 31712a1 commit 8e3620b
Showing 1 changed file with 20 additions and 23 deletions.
43 changes: 20 additions & 23 deletions rules/CodingStyle/Rector/PostInc/PostIncDecToPreIncDecRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\For_;
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 @@ -58,41 +57,35 @@ public function run($value = 1)
*/
public function getNodeTypes(): array
{
return [PostInc::class, PostDec::class];
return [For_::class, Expression::class];
}

/**
* @param PostInc|PostDec $node
* @param For_|Expression $node
*/
public function refactor(Node $node): ?Node
{
$parentNode = $node->getAttribute(AttributeKey::PARENT_NODE);
if ($this->isAnExpression($parentNode)) {
return $this->processPrePost($node);
if ($node instanceof Expression) {
return $this->refactorExpression($node);
}

if (! $parentNode instanceof For_) {
return null;
}
return $this->refactorFor($node);
}

if (count($parentNode->loop) !== 1) {
private function refactorFor(For_ $for): For_|null
{
if (count($for->loop) !== 1) {
return null;
}

if (! $this->nodeComparator->areNodesEqual($parentNode->loop[0], $node)) {
$singleLoopExpr = $for->loop[0];
if (! $singleLoopExpr instanceof PostInc && ! $singleLoopExpr instanceof PostDec) {
return null;
}

return $this->processPreFor($node, $parentNode);
}

private function isAnExpression(?Node $node = null): bool
{
if (! $node instanceof Node) {
return false;
}
$for->loop = [$this->processPrePost($singleLoopExpr)];

return $node instanceof Expression;
return $for;
}

private function processPrePost(PostInc | PostDec $node): PreInc | PreDec
Expand All @@ -104,9 +97,13 @@ private function processPrePost(PostInc | PostDec $node): PreInc | PreDec
return new PreDec($node->var);
}

private function processPreFor(PostInc | PostDec $node, For_ $for): PreDec | PreInc
private function refactorExpression(Expression $node): ?Expression
{
$for->loop = [$this->processPrePost($node)];
return $for->loop[0];
if ($node->expr instanceof PostInc || $node->expr instanceof PostDec) {
$node->expr = $this->processPrePost($node->expr);
return $node;
}

return null;
}
}

0 comments on commit 8e3620b

Please sign in to comment.