Skip to content

Commit

Permalink
Fix generalizing types in loops
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Aug 20, 2023
1 parent d435f65 commit c09be9e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -4657,10 +4657,10 @@ private static function generalizeType(Type $a, Type $b, int $depth): Type
TypeUtils::getAccessoryTypes($a),
);

return TypeCombinator::intersect(
return TypeCombinator::union(TypeCombinator::intersect(
TypeCombinator::union(...$resultTypes, ...$otherTypes),
...$accessoryTypes,
);
), ...$otherTypes);
}

private static function getArrayDepth(Type $type): int
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2378.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6294.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-2580.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9753.php');

if (PHP_VERSION_ID >= 80000) {
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-9721.php');
Expand Down
24 changes: 24 additions & 0 deletions tests/PHPStan/Analyser/data/bug-9753.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Bug9753;

use function PHPStan\Testing\assertType;

function (): void {
$items = [];
$array = [1,2,3,4,5];

foreach ($array as $entry) {
assertType('list<1|2|3|4|5>|null', $items);
if (isset($items)) {
if (count($items) > 2) {
$items = null;
} else {
$items[] = $entry;
}
}
assertType('list<1|2|3|4|5>|null', $items);
}

assertType('list<1|2|3|4|5>|null', $items);
};

0 comments on commit c09be9e

Please sign in to comment.