diff --git a/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var.php.inc b/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var.php.inc new file mode 100644 index 000000000000..a18807db65e3 --- /dev/null +++ b/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var.php.inc @@ -0,0 +1,16 @@ + diff --git a/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var2.php.inc b/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var2.php.inc new file mode 100644 index 000000000000..c033b5809bea --- /dev/null +++ b/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var2.php.inc @@ -0,0 +1,18 @@ + diff --git a/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var3.php.inc b/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var3.php.inc new file mode 100644 index 000000000000..2c76e80c6913 --- /dev/null +++ b/rules-tests/Php71/Rector/Assign/AssignArrayToStringRector/Fixture/skip_cast_undefined_var3.php.inc @@ -0,0 +1,20 @@ + diff --git a/rules/Php71/Rector/Assign/AssignArrayToStringRector.php b/rules/Php71/Rector/Assign/AssignArrayToStringRector.php index 3df18de98d2a..fd3dae644661 100644 --- a/rules/Php71/Rector/Assign/AssignArrayToStringRector.php +++ b/rules/Php71/Rector/Assign/AssignArrayToStringRector.php @@ -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; diff --git a/src/PhpParser/Node/BetterNodeFinder.php b/src/PhpParser/Node/BetterNodeFinder.php index 659656170f75..323e7763a5d6 100644 --- a/src/PhpParser/Node/BetterNodeFinder.php +++ b/src/PhpParser/Node/BetterNodeFinder.php @@ -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; @@ -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); }