Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Php56] Handle jump not Expression stmt next initialized on AddDefaultValueForUndefinedVariableRector #2725

Merged
merged 6 commits into from
Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace Rector\Tests\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector\Fixture;

class InitializedJumpNext
{
public function run()
{
if (rand(0, 1)) {
echo $a;
}

$a = null;

if (rand(0, 1)) {
$a = 5;
} else if (rand(0,1)) {
unset($a);
}

echo $a;
}
}

?>
-----
<?php

namespace Rector\Tests\Php56\Rector\FunctionLike\AddDefaultValueForUndefinedVariableRector\Fixture;

class InitializedJumpNext
{
public function run()
{
$a = null;
if (rand(0, 1)) {
echo $a;
}

$a = null;

if (rand(0, 1)) {
$a = 5;
} else if (rand(0,1)) {
unset($a);
}

echo $a;
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,25 @@ public function refactor(Node $node): ?Node
return $node;
}

/**
* @param Stmt[] $stmts
* @return Expression[]
*/
private function collectEarlyExpressionStmts(array $stmts): array
{
$expressionStmts = [];

foreach ($stmts as $stmt) {
if (! $stmt instanceof Expression) {
break;
}

$expressionStmts[] = $stmt;
}

return $expressionStmts;
}

/**
* @param string[] $undefinedVariableNames
* @param Stmt[] $stmts
Expand All @@ -121,6 +140,7 @@ public function refactor(Node $node): ?Node
private function collectVariablesInitiation(array $undefinedVariableNames, array $stmts): array
{
$variablesInitiation = [];
$expressionStmts = $this->collectEarlyExpressionStmts($stmts);

foreach ($undefinedVariableNames as $undefinedVariableName) {
$value = $this->isArray($undefinedVariableName, $stmts)
Expand All @@ -130,8 +150,8 @@ private function collectVariablesInitiation(array $undefinedVariableNames, array
$assign = new Assign(new Variable($undefinedVariableName), $value);
$expresssion = new Expression($assign);

foreach ($stmts as $stmt) {
if ($this->nodeComparator->areNodesEqual($expresssion, $stmt)) {
foreach ($expressionStmts as $expressionStmt) {
if ($this->nodeComparator->areNodesEqual($expresssion, $expressionStmt)) {
continue 2;
}
}
Expand Down