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

add tests, improve count behaviour on keyed arrays using integer range

This commit is contained in:
orklah 2021-09-04 23:14:50 +02:00
parent 7bf9df4360
commit a7fa63547e
2 changed files with 40 additions and 6 deletions

View File

@ -325,12 +325,23 @@ class FunctionCallReturnTypeFetcher
]);
}
if ($atomic_types['array'] instanceof Type\Atomic\TKeyedArray
&& $atomic_types['array']->isNonEmpty()
) {
return new Type\Union([
new Type\Atomic\TLiteralInt(count($atomic_types['array']->properties))
]);
if ($atomic_types['array'] instanceof Type\Atomic\TKeyedArray) {
$min = 0;
$max = 0;
foreach ($atomic_types['array']->properties as $property) {
if (!$property->possibly_undefined) {
$min++;
}
$max++;
}
if ($atomic_types['array']->sealed) {
//the KeyedArray is sealed, we can use the min and max
return new Type\Union([new Type\Atomic\TIntRange($min, $max)]);
} else {
//the type is not sealed, we can only use the min
return new Type\Union([new Type\Atomic\TIntRange($min, null)]);
}
}
return new Type\Union([

View File

@ -1103,6 +1103,29 @@ class TypeTest extends \Psalm\Tests\TestCase
}
',
],
'CountEqual0MakesNonEmptyArray' => [
'<?php
function a(array $a): void {
if (count($a) === 0) {
throw new \LogicException;
}
expectNonEmptyArray($a);
}
function b(array $a): void {
if (count($a) !== 0) {
expectNonEmptyArray($a);
}
}
function c(array $a): void {
if (count($a) === 0) {
throw new \LogicException;
} else {
expectNonEmptyArray($a);
}
}
/** @param non-empty-array $a */
function expectNonEmptyArray(array $a): array { return $a; }'
],
];
}