1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-22 05:41:20 +01:00

Fix #3017 - use correct keys when converting list to array

This commit is contained in:
Matt Brown 2020-11-27 20:05:16 -05:00 committed by Daniil Gentili
parent 3005d2e1d7
commit 5cf5aecb2f
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
2 changed files with 34 additions and 1 deletions

View File

@ -12,6 +12,8 @@ use Psalm\Type\Atomic\TLiteralInt;
use Psalm\Type\Atomic\TLiteralString;
use Psalm\Type\Atomic\TNonEmptyArray;
use Psalm\Type\Atomic\TNonEmptyList;
use function array_map;
use function range;
/**
* @internal
@ -148,7 +150,22 @@ class ArrayTypeComparator
if ($input_type_part instanceof TList) {
if ($input_type_part instanceof TNonEmptyList) {
$input_type_part = new TNonEmptyArray([Type::getInt(), clone $input_type_part->type_param]);
// if the array has a known size < 10, make sure the array keys are literal ints
if ($input_type_part->count !== null && $input_type_part->count < 10) {
$literal_ints = array_map(
function ($i) {
return new Type\Atomic\TLiteralInt($i);
},
range(0, $input_type_part->count - 1)
);
$input_type_part = new TNonEmptyArray([
new Type\Union($literal_ints),
clone $input_type_part->type_param
]);
} else {
$input_type_part = new TNonEmptyArray([Type::getInt(), clone $input_type_part->type_param]);
}
} else {
$input_type_part = new TArray([Type::getInt(), clone $input_type_part->type_param]);
}

View File

@ -1057,6 +1057,22 @@ class TypeTest extends \Psalm\Tests\TestCase
strlen($s);
}'
],
'narrowWithCountToAllowNonTupleKeyedArray' => [
'<?php
/**
* @param list<string> $arr
*/
function foo($arr): void {
if (count($arr) === 2) {
consume($arr);
}
}
/**
* @param array{0:string, 1: string} $input
*/
function consume($input): void{}'
],
];
}