[CodingStyle] Re-use assigned variable for Method/Static/FuncCall/New_ on SplitDoubleAssignRector (#4968)

This commit is contained in:
Abdul Malik Ikhsan 2020-12-24 03:42:40 +07:00 committed by GitHub
parent aa35633c66
commit 8a648216ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 89 additions and 2 deletions

View File

@ -5,8 +5,15 @@ declare(strict_types=1);
namespace Rector\CodingStyle\Rector\Assign;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Stmt\Expression;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -59,14 +66,42 @@ CODE_SAMPLE
*/
public function refactor(Node $node): ?Node
{
$parent = $node->getAttribute(AttributeKey::PARENT_NODE);
if (! $parent instanceof Expression) {
return null;
}
if (! $node->expr instanceof Assign) {
return null;
}
$newAssign = new Assign($node->var, $node->expr->expr);
$this->addNodeAfterNode($node->expr, $node);
if (! $this->isExprCallOrNew($node->expr->expr)) {
$this->addNodeAfterNode($node->expr, $node);
return $newAssign;
}
return $newAssign;
$varAssign = new Assign($node->expr->var, $node->var);
$this->addNodeBeforeNode(new Expression($newAssign), $node);
return $varAssign;
}
private function isExprCallOrNew(Expr $expr): bool
{
if ($expr instanceof MethodCall) {
return true;
}
if ($expr instanceof StaticCall) {
return true;
}
if ($expr instanceof FuncCall) {
return true;
}
return $expr instanceof New_;
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Rector\CodingStyle\Tests\Rector\Assign\SplitDoubleAssignRector\Fixture;
class SkipAssignInNonExpression
{
public function run()
{
if ($one = $two = 1) {
}
}
}
?>

View File

@ -0,0 +1,37 @@
<?php
namespace Rector\CodingStyle\Tests\Rector\Assign\SplitDoubleAssignRector\Fixture;
class UsePrevAssignVarCallNew
{
public function run()
{
$one = $two = $this->execute();
$one = $two = self::execute();
$one = $two = execute();
$one = $two = new \stdClass;
}
}
?>
-----
<?php
namespace Rector\CodingStyle\Tests\Rector\Assign\SplitDoubleAssignRector\Fixture;
class UsePrevAssignVarCallNew
{
public function run()
{
$one = $this->execute();
$two = $one;
$one = self::execute();
$two = $one;
$one = execute();
$two = $one;
$one = new \stdClass;
$two = $one;
}
}
?>