Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve return type of array_fill_keys for not constant arrays #1145

Merged
merged 1 commit into from
Mar 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/Type/Php/ArrayFillKeysFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
$keysType = $scope->getType($functionCall->getArgs()[0]->value);
$constantArrays = TypeUtils::getConstantArrays($keysType);
if (count($constantArrays) === 0) {
if ($keysType->isArray()->yes()) {
$itemType = $keysType->getIterableValueType();

if ((new IntegerType())->isSuperTypeOf($itemType)->no()) {
if ($itemType->toString() instanceof ErrorType) {
return new ArrayType($itemType, $valueType);
}

return new ArrayType($itemType->toString(), $valueType);
}
}

return new ArrayType($keysType->getIterableValueType(), $valueType);
}

Expand Down
16 changes: 16 additions & 0 deletions tests/PHPStan/Analyser/data/array-fill-keys.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,19 @@ function withObjectKey() : array
assertType("non-empty-array<string, 'b'>", array_fill_keys([new Bar()], 'b'));
assertType("*NEVER*", array_fill_keys([new Baz()], 'b'));
}

/**
* @param Bar[] $foo
* @param int[] $bar
* @param Foo[] $baz
* @param float[] $floats
* @param array<int, int|string|bool> $mixed
*/
function withNotConstantArray(array $foo, array $bar, array $baz, array $floats, array $mixed): void
{
assertType("array<string, null>", array_fill_keys($foo, null));
assertType("array<int, null>", array_fill_keys($bar, null));
assertType("array<'foo', null>", array_fill_keys($baz, null));
assertType("array<numeric-string, null>", array_fill_keys($floats, null));
assertType("array<bool|int|string, null>", array_fill_keys($mixed, null));
}