1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 04:45:20 +01:00

Fix ArrayFillReturnTypeProvider - consider second param (#5770)

Add test

Fix
This commit is contained in:
olsavmic 2021-05-15 02:12:39 +02:00 committed by GitHub
parent 5f780e7ef7
commit 4fb2b65164
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 8 deletions

View File

@ -23,24 +23,39 @@ class ArrayFillReturnTypeProvider implements \Psalm\Plugin\EventHandler\Function
}
$first_arg_type = isset($call_args[0]) ? $statements_source->node_data->getType($call_args[0]->value) : null;
$second_arg_type = isset($call_args[1]) ? $statements_source->node_data->getType($call_args[1]->value) : null;
$third_arg_type = isset($call_args[2]) ? $statements_source->node_data->getType($call_args[2]->value) : null;
if ($third_arg_type) {
if ($first_arg_type
&& $first_arg_type->isSingleIntLiteral()
&& $first_arg_type->getSingleIntLiteral()->value === 0
$value_type_from_third_arg = $third_arg_type ? clone $third_arg_type : Type::getMixed();
if ($first_arg_type
&& $first_arg_type->isSingleIntLiteral()
&& $first_arg_type->getSingleIntLiteral()->value === 0
) {
if ($second_arg_type
&& self::isPositiveNumericType($second_arg_type)
) {
return new Type\Union([
new Type\Atomic\TNonEmptyList(
clone $third_arg_type
$value_type_from_third_arg
)
]);
}
return new Type\Union([
new Type\Atomic\TArray([
new Type\Atomic\TList(
$value_type_from_third_arg
)
]);
}
if ($second_arg_type
&& self::isPositiveNumericType($second_arg_type)
) {
return new Type\Union([
new Type\Atomic\TNonEmptyArray([
Type::getInt(),
clone $third_arg_type
$value_type_from_third_arg,
])
]);
}
@ -48,8 +63,16 @@ class ArrayFillReturnTypeProvider implements \Psalm\Plugin\EventHandler\Function
return new Type\Union([
new Type\Atomic\TArray([
Type::getInt(),
Type::getMixed()
$value_type_from_third_arg,
])
]);
}
private static function isPositiveNumericType (Type\Union $arg): bool {
if ($arg->isSingle() && $arg->hasPositiveInt()) {
return true;
}
return $arg->isSingleIntLiteral() && $arg->getSingleIntLiteral()->value > 0;
}
}

View File

@ -909,6 +909,10 @@ class ArrayFunctionCallTest extends TestCase
return "a";
}',
],
'arrayFillZeroLength' => [
'<?php
count(array_fill(0, 0, 0)) === 0;',
],
'implodeMultiDimensionalArray' => [
'<?php
$urls = array_map("implode", [["a", "b"]]);',
@ -1953,6 +1957,11 @@ class ArrayFunctionCallTest extends TestCase
array_filter(["hello"], "foo");',
'error_message' => 'InvalidScalarArgument',
],
'arrayFillPositiveConstantLength' => [
'<?php
count(array_fill(0, 1, 0)) === 0;',
'error_message' => 'TypeDoesNotContainType'
],
'arrayFilterTooFewArgs' => [
'<?php
function foo(int $i, string $s) : bool {