Skip to content

Commit

Permalink
[Php71] Skip AssignArrayToStringRector on assign var not defined befo…
Browse files Browse the repository at this point in the history
…re (#5985)
  • Loading branch information
samsonasik authored Mar 24, 2021
1 parent cee8046 commit 45f6570
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\Php71\Rector\Assign\AssignArrayToStringRector\Fixture;

class SkipCastUndefinedVar
{
public function fun()
{
$array[] = 'foo';
$array[] = 'bar';

return $array;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\Tests\Php71\Rector\Assign\AssignArrayToStringRector\Fixture;

class SkipCastUndefinedVar2
{
private $array;

public function fun()
{
$array[] = 'foo';
$array[] = 'bar';

return $array;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Rector\Tests\Php71\Rector\Assign\AssignArrayToStringRector\Fixture;

class SkipCastUndefinedVar3
{
public function fun()
{
$array = [];

function () {
$array[] = 'foo';
$array[] = 'bar';

return $array;
};
}
}

?>
10 changes: 9 additions & 1 deletion rules/Php71/Rector/Assign/AssignArrayToStringRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,17 @@ public function refactor(Node $node): ?Node
return $node;
}

$isFoundPrev = (bool) $this->betterNodeFinder->findFirstPreviousOfNode($variable, function (Node $node) use ($variable): bool {
return $this->nodeComparator->areNodesEqual($node, $variable);
});

if (! $isFoundPrev) {
return null;
}

// there is "$string[] = ...;", which would cause error in PHP 7+
// fallback - if no array init found, retype to (array)
$assign = new Assign($arrayDimFetchNode->var, new ArrayCast($arrayDimFetchNode->var));
$assign = new Assign($variable, new ArrayCast($variable));
$this->addNodeAfterNode(clone $node, $node);

return $assign;
Expand Down
5 changes: 5 additions & 0 deletions src/PhpParser/Node/BetterNodeFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
Expand Down Expand Up @@ -280,6 +281,10 @@ public function findFirstPreviousOfNode(Node $node, callable $filter): ?Node
}

$parent = $node->getAttribute(AttributeKey::PARENT_NODE);
if ($parent instanceof FunctionLike) {
return null;
}

if ($parent instanceof Node) {
return $this->findFirstPreviousOfNode($parent, $filter);
}
Expand Down

0 comments on commit 45f6570

Please sign in to comment.