Skip to content

Commit 84fe920

Browse files
authored
[CodeQuality] Skip possibly undefined variable on CoalesceToTernaryRector (#7968)
1 parent 6200bab commit 84fe920

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\Coalesce\CoalesceToTernaryRector\Fixture;
4+
5+
class SkipPossiblyUndefined
6+
{
7+
public function run()
8+
{
9+
if (rand(0, 1)) {
10+
$name = 'tom';
11+
}
12+
13+
return $name ?? 'tom';
14+
}
15+
}

rules/CodeQuality/Rector/Coalesce/CoalesceToTernaryRector.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use PhpParser\Node\Expr\ArrayDimFetch;
99
use PhpParser\Node\Expr\BinaryOp\Coalesce;
1010
use PhpParser\Node\Expr\Ternary;
11+
use PhpParser\Node\Expr\Variable;
1112
use PHPStan\Type\ErrorType;
1213
use PHPStan\Type\MixedType;
1314
use PHPStan\Type\NullType;
@@ -92,6 +93,10 @@ public function refactor(Node $node): ?Node
9293
}
9394
}
9495

96+
if ($node->left instanceof Variable && ! $scope->hasVariableType((string) $this->getName($node->left))->yes()) {
97+
return null;
98+
}
99+
95100
return new Ternary($node->left, null, $node->right);
96101
}
97102
}

0 commit comments

Comments
 (0)