Skip to content

Commit

Permalink
[CodeQuality] Skip static variable on SimplifyUselessVariableRector (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
samsonasik committed Aug 9, 2021
1 parent fa8e3bd commit c3e0ff3
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 2 deletions.
@@ -0,0 +1,15 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Return_\SimplifyUselessVariableRector\Fixture;

class SkipStaticVariable
{
public function run()
{
static $content;

$content .= 'test';

return $content;
}
}
12 changes: 10 additions & 2 deletions rules/CodeQuality/Rector/Return_/SimplifyUselessVariableRector.php
Expand Up @@ -13,6 +13,7 @@
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use PHPStan\Type\MixedType;
use Rector\Core\NodeAnalyzer\VariableAnalyzer;
use Rector\Core\PhpParser\Node\AssignAndBinaryMap;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
Expand All @@ -26,7 +27,8 @@
final class SimplifyUselessVariableRector extends AbstractRector
{
public function __construct(
private AssignAndBinaryMap $assignAndBinaryMap
private AssignAndBinaryMap $assignAndBinaryMap,
private VariableAnalyzer $variableAnalyzer
) {
}

Expand Down Expand Up @@ -125,6 +127,7 @@ private function shouldSkip(Return_ $return): bool
return true;
}

/** @var Variable $variableNode */
$variableNode = $return->expr;

$previousExpression = $return->getAttribute(AttributeKey::PREVIOUS_NODE);
Expand All @@ -145,7 +148,12 @@ private function shouldSkip(Return_ $return): bool
if (! $this->nodeComparator->areNodesEqual($previousNode->var, $variableNode)) {
return true;
}
return $this->isPreviousExpressionVisuallySimilar($previousExpression, $previousNode);

if ($this->isPreviousExpressionVisuallySimilar($previousExpression, $previousNode)) {
return true;
}

return $this->variableAnalyzer->isStatic($variableNode);
}

private function hasSomeComment(Expr $expr): bool
Expand Down
39 changes: 39 additions & 0 deletions src/NodeAnalyzer/VariableAnalyzer.php
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Rector\Core\NodeAnalyzer;

use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Static_;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\Core\PhpParser\Node\BetterNodeFinder;

final class VariableAnalyzer
{
public function __construct(
private BetterNodeFinder $betterNodeFinder,
private NodeComparator $nodeComparator
) {
}

public function isStatic(Variable $variable): bool
{
return (bool) $this->betterNodeFinder->findFirstPreviousOfNode($variable, function (Node $n) use (
$variable
): bool {
if (! $n instanceof Static_) {
return false;
}

foreach ($n->vars as $staticVar) {
if ($this->nodeComparator->areNodesEqual($staticVar->var, $variable)) {
return true;
}
}

return false;
});
}
}

0 comments on commit c3e0ff3

Please sign in to comment.