1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-26 20:34:47 +01:00

Ref #4753 - allow int literals to inform key type

This commit is contained in:
Matt Brown 2020-12-02 17:13:45 -05:00 committed by Daniil Gentili
parent a20db1ce34
commit 1780541501
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
3 changed files with 30 additions and 0 deletions

View File

@ -3755,6 +3755,10 @@ class AssertionFinder
foreach ($key_type->getLiteralStrings() as $array_literal_type) {
$literal_assertions[] = '=' . $array_literal_type->getId();
}
} elseif ($key_type->allIntLiterals() && !$key_type->possibly_undefined) {
foreach ($key_type->getLiteralInts() as $array_literal_type) {
$literal_assertions[] = '=' . $array_literal_type->getId();
}
}
}
}

View File

@ -1196,6 +1196,17 @@ class Union implements TypeNode
return true;
}
public function allIntLiterals() : bool
{
foreach ($this->types as $atomic_key_type) {
if (!$atomic_key_type instanceof TLiteralInt) {
return false;
}
}
return true;
}
public function hasLiteralValue() : bool
{
return $this->literal_int_types

View File

@ -312,6 +312,21 @@ class ArrayKeyExistsTest extends \Psalm\Tests\TestCase
return false;
}'
],
'allowIntKeysToo' => [
'<?php
/**
* @param array<1|2|3, string> $arr
* @return 1|2|3
*/
function checkArrayKeyExistsInt(array $arr, int $int): int
{
if (array_key_exists($int, $arr)) {
return $int;
}
return 1;
}'
],
];
}