Skip to content

Commit a093a2a

Browse files
committed
infer non-empty-list/array after array_key_exists($i, $arr)
1 parent 6e498e6 commit a093a2a

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

src/Type/Php/ArrayKeyExistsFunctionTypeSpecifyingExtension.php

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,15 @@ public function specifyTypes(
6666
&& !$keyType instanceof ConstantStringType
6767
) {
6868
if ($context->true()) {
69+
$specifiedTypes = $this->typeSpecifier->create(
70+
$array,
71+
new NonEmptyArrayType(),
72+
$context,
73+
$scope,
74+
);
75+
6976
if ($arrayType->isIterableAtLeastOnce()->no()) {
70-
return $this->typeSpecifier->create(
71-
$array,
72-
new NonEmptyArrayType(),
73-
$context,
74-
$scope,
75-
);
77+
return $specifiedTypes;
7678
}
7779

7880
$arrayKeyType = $arrayType->getIterableKeyType();
@@ -82,12 +84,12 @@ public function specifyTypes(
8284
$arrayKeyType = TypeCombinator::union($arrayKeyType, $arrayKeyType->toString());
8385
}
8486

85-
$specifiedTypes = $this->typeSpecifier->create(
87+
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
8688
$key,
8789
$arrayKeyType,
8890
$context,
8991
$scope,
90-
);
92+
));
9193

9294
$arrayDimFetch = new ArrayDimFetch(
9395
$array,

tests/PHPStan/Rules/Arrays/data/slevomat-foreach-array-key-exists-bug.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public function doFoo(array $percentageIntervals, array $changes): void
1515
if ($percentageInterval->isInInterval((float) $changeInPercents)) {
1616
$key = $percentageInterval->getFormatted();
1717
if (array_key_exists($key, $intervalResults)) {
18-
assertType('array<array{itemsCount: mixed, interval: mixed}>', $intervalResults);
18+
assertType('non-empty-array<array{itemsCount: mixed, interval: mixed}>', $intervalResults);
1919
assertType('array{itemsCount: mixed, interval: mixed}', $intervalResults[$key]);
2020
$intervalResults[$key]['itemsCount'] += $itemsCount;
2121
assertType('non-empty-array<array{itemsCount: (array|float|int), interval: mixed}>', $intervalResults);

0 commit comments

Comments
 (0)