Skip to content

Commit dbdcb81

Browse files
committed
ConstantArrayTypeBuilder - generalize key types and value types in degraded general array
1 parent 10ba3c6 commit dbdcb81

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/Type/ArrayType.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $uni
293293
}
294294
}
295295

296-
$array = new self($keyType, $itemType,);
296+
$array = new self($keyType, $itemType);
297297
if ($offsetType instanceof ConstantIntegerType || $offsetType instanceof ConstantStringType) {
298298
return TypeCombinator::intersect($array, new HasOffsetValueType($offsetType, $valueType), new NonEmptyArrayType());
299299
}

src/Type/Constant/ConstantArrayTypeBuilder.php

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use PHPStan\ShouldNotHappenException;
66
use PHPStan\Type\Accessory\NonEmptyArrayType;
77
use PHPStan\Type\ArrayType;
8+
use PHPStan\Type\GeneralizePrecision;
89
use PHPStan\Type\Type;
910
use PHPStan\Type\TypeCombinator;
1011
use PHPStan\Type\TypeUtils;
@@ -266,10 +267,16 @@ public function getArray(): Type
266267
return new ConstantArrayType($keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys);
267268
}
268269

269-
$array = new ArrayType(
270-
TypeCombinator::union(...$this->keyTypes),
271-
TypeCombinator::union(...$this->valueTypes),
272-
);
270+
$keyType = TypeCombinator::union(...$this->keyTypes);
271+
if (count(TypeUtils::getConstantScalars($keyType)) > self::ARRAY_COUNT_LIMIT) {
272+
$keyType = $keyType->generalize(GeneralizePrecision::moreSpecific());
273+
}
274+
$valueType = TypeCombinator::union(...$this->valueTypes);
275+
if (count(TypeUtils::getConstantScalars($valueType)) > self::ARRAY_COUNT_LIMIT) {
276+
$valueType = $valueType->generalize(GeneralizePrecision::moreSpecific());
277+
}
278+
279+
$array = new ArrayType($keyType, $valueType);
273280

274281
if (count($this->optionalKeys) < $keyTypesCount) {
275282
return TypeCombinator::intersect($array, new NonEmptyArrayType());

0 commit comments

Comments
 (0)