mirror of
https://github.com/rectorphp/rector.git
synced 2025-01-19 06:18:07 +01:00
[Php71] Skip AssignArrayToStringRector on assign var not defined before (#5985)
This commit is contained in:
parent
cee8046e84
commit
45f657004f
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Rector\Tests\Php71\Rector\Assign\AssignArrayToStringRector\Fixture;
|
||||
|
||||
class SkipCastUndefinedVar
|
||||
{
|
||||
public function fun()
|
||||
{
|
||||
$array[] = 'foo';
|
||||
$array[] = 'bar';
|
||||
|
||||
return $array;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
@ -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;
|
||||
|
@ -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);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user