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] Skip AddDefaultValueForUndefinedVariableRector as coalesce left #1238

Merged
merged 2 commits into from
Nov 15, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

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

class SkipCoalesce
{
public function run()
{
if (rand(0,1)) {
$value = 'value';
}

return $value ?? 'test';
}
}
10 changes: 10 additions & 0 deletions rules/Php56/NodeAnalyzer/UndefinedVariableResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\Expr\Cast\Unset_ as UnsetCast;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\Isset_;
Expand Down Expand Up @@ -114,6 +115,11 @@ private function issetOrUnsetParent(Node $parentNode): bool
return in_array($parentNode::class, [Unset_::class, UnsetCast::class, Isset_::class], true);
}

private function isAsCoalesceLeft(Node $parentNode, Variable $variable): bool
{
return $parentNode instanceof Coalesce && $parentNode->left === $variable;
}

private function isAssignOrStaticVariableParent(Node $parentNode): bool
{
if (in_array($parentNode::class, [Assign::class, AssignRef::class], true)) {
Expand Down Expand Up @@ -142,6 +148,10 @@ private function shouldSkipVariable(Variable $variable): bool
return true;
}

if ($this->isAsCoalesceLeft($parentNode, $variable)) {
return true;
}

// list() = | [$values] = defines variables as null
if ($this->isListAssign($parentNode)) {
return true;
Expand Down