Skip to content

Commit

Permalink
[Php56] Skip AddDefaultValueForUndefinedVariableRector as coalesce le…
Browse files Browse the repository at this point in the history
…ft (#1238)

* [Php56] Skip FAddDefaultValueForUndefinedVariableRector in coalesce

* Fixed 🎉
  • Loading branch information
samsonasik authored Nov 15, 2021
1 parent 5154b53 commit 80e0123
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
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

0 comments on commit 80e0123

Please sign in to comment.