Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c09be9e

Browse files
committed
Fix generalizing types in loops
1 parent d435f65 commit c09be9e

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

src/Analyser/MutatingScope.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4657,10 +4657,10 @@ private static function generalizeType(Type $a, Type $b, int $depth): Type
46574657
TypeUtils::getAccessoryTypes($a),
46584658
);
46594659

4660-
return TypeCombinator::intersect(
4660+
return TypeCombinator::union(TypeCombinator::intersect(
46614661
TypeCombinator::union(...$resultTypes, ...$otherTypes),
46624662
...$accessoryTypes,
4663-
);
4663+
), ...$otherTypes);
46644664
}
46654665

46664666
private static function getArrayDepth(Type $type): int

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ public function dataFileAsserts(): iterable
227227
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2378.php');
228228
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6294.php');
229229
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2580.php');
230+
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9753.php');
230231

231232
if (PHP_VERSION_ID >= 80000) {
232233
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9721.php');
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace Bug9753;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
function (): void {
8+
$items = [];
9+
$array = [1,2,3,4,5];
10+
11+
foreach ($array as $entry) {
12+
assertType('list<1|2|3|4|5>|null', $items);
13+
if (isset($items)) {
14+
if (count($items) > 2) {
15+
$items = null;
16+
} else {
17+
$items[] = $entry;
18+
}
19+
}
20+
assertType('list<1|2|3|4|5>|null', $items);
21+
}
22+
23+
assertType('list<1|2|3|4|5>|null', $items);
24+
};

0 commit comments

Comments
 (0)