Skip to content

Commit fc69708

Browse files
authored
Use TypeUtils::getOldConstantArrays in array_fill_keys extension
1 parent 169af1d commit fc69708

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/Type/Php/ArrayFillKeysFunctionReturnTypeExtension.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
3333

3434
$valueType = $scope->getType($functionCall->getArgs()[1]->value);
3535
$keysType = $scope->getType($functionCall->getArgs()[0]->value);
36-
$constantArrays = TypeUtils::getConstantArrays($keysType);
36+
$constantArrays = TypeUtils::getOldConstantArrays($keysType);
3737
if (count($constantArrays) === 0) {
3838
if ($keysType->isArray()->yes()) {
3939
$itemType = $keysType->getIterableValueType();
@@ -53,15 +53,15 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
5353
$arrayTypes = [];
5454
foreach ($constantArrays as $constantArray) {
5555
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
56-
foreach ($constantArray->getValueTypes() as $keyType) {
56+
foreach ($constantArray->getValueTypes() as $i => $keyType) {
5757
if ((new IntegerType())->isSuperTypeOf($keyType)->no()) {
5858
if ($keyType->toString() instanceof ErrorType) {
5959
return new NeverType();
6060
}
6161

62-
$arrayBuilder->setOffsetValueType($keyType->toString(), $valueType);
62+
$arrayBuilder->setOffsetValueType($keyType->toString(), $valueType, $constantArray->isOptionalKey($i));
6363
} else {
64-
$arrayBuilder->setOffsetValueType($keyType, $valueType);
64+
$arrayBuilder->setOffsetValueType($keyType, $valueType, $constantArray->isOptionalKey($i));
6565
}
6666
}
6767
$arrayTypes[] = $arrayBuilder->getArray();

tests/PHPStan/Analyser/data/array-fill-keys.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,28 @@ function withObjectKey() : array
5151
assertType("*NEVER*", array_fill_keys([new Baz()], 'b'));
5252
}
5353

54+
function withUnionKeys(): void
55+
{
56+
$arr1 = ['foo', rand(0, 1) ? 'bar1' : 'bar2', 'baz'];
57+
assertType("non-empty-array<'bar1'|'bar2'|'baz'|'foo', 'b'>", array_fill_keys($arr1, 'b'));
58+
59+
$arr2 = ['foo'];
60+
if (rand(0, 1)) {
61+
$arr2[] = 'bar';
62+
}
63+
$arr2[] = 'baz';
64+
assertType("non-empty-array<'bar'|'baz'|'foo', 'b'>", array_fill_keys($arr2, 'b'));
65+
}
66+
67+
function withOptionalKeys(): void
68+
{
69+
$arr1 = ['foo', 'bar'];
70+
if (rand(0, 1)) {
71+
$arr1[] = 'baz';
72+
}
73+
assertType("array{foo: 'b', bar: 'b', baz?: 'b'}", array_fill_keys($arr1, 'b'));
74+
}
75+
5476
/**
5577
* @param Bar[] $foo
5678
* @param int[] $bar

0 commit comments

Comments
 (0)