Skip to content

Commit c2be58d

Browse files
[CodeQuality] Skip possibly undefined variable on SimplifyEmptyCheckOnEmptyArrayRector (#8006)
* [CodeQuality] Skip possibly undefined variable on SimplifyEmptyCheckOnEmptyArrayRector * fix * [ci-review] Rector Rectify --------- Co-authored-by: GitHub Action <actions@github.com>
1 parent 74c4907 commit c2be58d

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector\Fixture;
4+
5+
class SkipPossiblyUndefinedVariable
6+
{
7+
public function run(bool $cond): array
8+
{
9+
if ($cond) {
10+
$map = ['a' => 1];
11+
}
12+
13+
// empty() tolerates an undefined $map; `$map === []` does not.
14+
if (empty($map)) {
15+
return [];
16+
}
17+
18+
return $map;
19+
}
20+
}

src/NodeAnalyzer/ExprAnalyzer.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,16 @@
5454
use PHPStan\Type\ObjectWithoutClassType;
5555
use PHPStan\Type\UnionType;
5656
use Rector\Enum\ObjectReference;
57+
use Rector\NodeNameResolver\NodeNameResolver;
5758
use Rector\NodeTypeResolver\Node\AttributeKey;
5859

59-
final class ExprAnalyzer
60+
final readonly class ExprAnalyzer
6061
{
62+
public function __construct(
63+
private NodeNameResolver $nodeNameResolver
64+
) {
65+
}
66+
6167
public function isBoolExpr(Expr $expr): bool
6268
{
6369
return $expr instanceof BooleanNot
@@ -158,6 +164,10 @@ public function isNonTypedFromParam(Expr $expr): bool
158164
return true;
159165
}
160166

167+
if (! $scope->hasVariableType((string) $this->nodeNameResolver->getName($expr))->yes()) {
168+
return true;
169+
}
170+
161171
if ($nativeType instanceof UnionType) {
162172
return ! $nativeType->equals($type);
163173
}

0 commit comments

Comments
 (0)