Skip to content

Commit 9283da5

Browse files
committed
add more tests, simplify impl
1 parent eebb9fb commit 9283da5

File tree

2 files changed

+42
-9
lines changed

2 files changed

+42
-9
lines changed

src/Type/IntersectionType.php

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -683,17 +683,17 @@ public function getArraySize(): Type
683683
{
684684
$arraySize = $this->intersectTypes(static fn (Type $type): Type => $type->getArraySize());
685685

686-
if ($arraySize instanceof IntegerRangeType) {
687-
$knownOffsets = [];
688-
foreach ($this->types as $type) {
689-
if (!($type instanceof HasOffsetValueType) && !($type instanceof HasOffsetType)) {
690-
continue;
691-
}
692-
693-
$knownOffsets[$type->getOffsetType()->getValue()] = true;
686+
$knownOffsets = [];
687+
foreach ($this->types as $type) {
688+
if (!($type instanceof HasOffsetValueType) && !($type instanceof HasOffsetType)) {
689+
continue;
694690
}
695691

696-
return IntegerRangeType::fromInterval(max(count($knownOffsets), $arraySize->getMin()), $arraySize->getMax());
692+
$knownOffsets[$type->getOffsetType()->getValue()] = true;
693+
}
694+
695+
if ($knownOffsets !== []) {
696+
return TypeCombinator::intersect($arraySize, IntegerRangeType::fromInterval(count($knownOffsets), null));
697697
}
698698

699699
return $arraySize;

tests/PHPStan/Analyser/nsrt/count-recursive.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,24 @@ public function countListRecursive($list): void
130130
}
131131
}
132132

133+
/** @param arary<int> $array */
134+
public function countListRecursiveOnUnionOfRanges($array): void
135+
{
136+
if (!array_key_exists(5, $array)) {
137+
return;
138+
}
139+
assertType('non-empty-array&hasOffset(5)', $array);
140+
assertType('int<1, max>', count($array));
141+
142+
if (
143+
(count($array) > 2 && count($array) < 5)
144+
|| (count($array) > 20 && count($array) < 50)
145+
) {
146+
assertType('int<3, 4>|int<21, 49>', count($array));
147+
}
148+
}
149+
150+
133151
public function countConstantArray(array $anotherArray): void {
134152
$arr = [1, 2, 3, [4, 5]];
135153
assertType('4', count($arr));
@@ -177,4 +195,19 @@ public function countAfterKeyExists(array $array, int $i): void {
177195
}
178196
}
179197
}
198+
199+
public function unionIntegerCountAfterKeyExists(array $array, int $i): void {
200+
if ($array === []) {
201+
return;
202+
}
203+
204+
assertType('non-empty-array', $array);
205+
if (count($array) === 3 || count($array) === 4) {
206+
assertType('3|4', count($array));
207+
if (array_key_exists(5, $array)) {
208+
assertType('non-empty-array&hasOffset(5)', $array);
209+
assertType('3|4', count($array));
210+
}
211+
}
212+
}
180213
}

0 commit comments

Comments
 (0)