Skip to content

Commit 018c13e

Browse files
committed
Fix phpstan/phpstan#13526: False positive with array_key_exists and union types
1 parent 4b2e7e5 commit 018c13e

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

src/Analyser/MutatingScope.php

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3680,10 +3680,6 @@ public function addTypeToExpression(Expr $expr, Type $type): self
36803680

36813681
if ($originalExprType->equals($nativeType)) {
36823682
$newType = TypeCombinator::intersect($type, $originalExprType);
3683-
if ($newType->isConstantScalarValue()->yes() && $newType->equals($originalExprType)) {
3684-
// don't add the same type over and over again to improve performance
3685-
return $this;
3686-
}
36873683
return $this->specifyExpressionType($expr, $newType, $newType, TrinaryLogic::createYes());
36883684
}
36893685

tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,4 +1155,10 @@ public function testBug11276(): void
11551155
$this->analyse([__DIR__ . '/data/bug-11276.php'], []);
11561156
}
11571157

1158+
public function testBug13526(): void
1159+
{
1160+
$this->reportPossiblyNonexistentConstantArrayOffset = true;
1161+
$this->analyse([__DIR__ . '/data/bug-13526.php'], []);
1162+
}
1163+
11581164
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Bug13526;
4+
5+
class Foo
6+
{
7+
public function foo(string $item, bool $a): ?int
8+
{
9+
$map1 = [
10+
'MAP_1_ITEM_1' => 1,
11+
'MAP_1_ITEM_2' => 2,
12+
];
13+
$map2 = [
14+
'MAP_2_ITEM_1' => 1,
15+
'MAP_2_ITEM_2' => 2,
16+
];
17+
18+
$map = $a ? $map1 : $map2;
19+
20+
if (array_key_exists($item, $map)) {
21+
return $map[$item];
22+
}
23+
24+
return null;
25+
}
26+
}

0 commit comments

Comments
 (0)