[Php71] Skip AssignArrayToStringRector on assign var not defined before (#5985)

This commit is contained in:
Abdul Malik Ikhsan 2021-03-25 05:36:56 +07:00 committed by GitHub
parent cee8046e84
commit 45f657004f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 68 additions and 1 deletions

View File

@ -0,0 +1,16 @@
<?php
namespace Rector\Tests\Php71\Rector\Assign\AssignArrayToStringRector\Fixture;
class SkipCastUndefinedVar
{
public function fun()
{
$array[] = 'foo';
$array[] = 'bar';
return $array;
}
}
?>

View File

@ -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;
}
}
?>

View File

@ -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;
};
}
}
?>

View File

@ -105,9 +105,17 @@ CODE_SAMPLE
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;

View File

@ -8,6 +8,7 @@ use PhpParser\Node;
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;
@ -280,6 +281,10 @@ final class BetterNodeFinder
}
$parent = $node->getAttribute(AttributeKey::PARENT_NODE);
if ($parent instanceof FunctionLike) {
return null;
}
if ($parent instanceof Node) {
return $this->findFirstPreviousOfNode($parent, $filter);
}