Skip to content

Commit

Permalink
['15' => 'a'] is internally [15 => 'a']
Browse files Browse the repository at this point in the history
  • Loading branch information
kkmuffme committed Mar 15, 2024
1 parent 4ea41cb commit 69aa389
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
5 changes: 4 additions & 1 deletion src/Psalm/Internal/Type/Comparator/KeyedArrayComparator.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use function array_keys;
use function is_string;
use function preg_match;

/**
* @internal
Expand Down Expand Up @@ -166,7 +167,9 @@ public static function isContainedBy(
$key_type_comparison = new TypeComparisonResult();
if (!UnionTypeComparator::isContainedBy(
$codebase,
is_string($key) ? Type::getString($key) : Type::getInt(false, $key),
is_string($key) && preg_match('/^\d+$/', $key) !== 1
? Type::getString($key)
: Type::getInt(false, (int) $key),
$key_type,
false,
false,
Expand Down
35 changes: 24 additions & 11 deletions tests/ArrayKeysTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,36 +130,36 @@ public function test(): array {
* @psalm-type TAlias = 123
*/
class a {}
/**
* @psalm-import-type TAlias from a
* @template TKey as array-key
* @template TValue as array-key
* @template T as array<TKey, TValue>
*
*
* @template TOrig as a|b
* @template TT as class-string<TOrig>
*
*
* @template TBool as bool
*/
class b {
/**
* @var array<TAlias, int>
/**
* @var array<TAlias, int>
*/
private array $a = [123 => 123];
/** @var array<value-of<T>, int> */
public array $c = [];
/** @var array<key-of<T>, int> */
public array $d = [];
/** @var array<TT, int> */
public array $e = [];
/** @var array<key-of<array<int, string>>, int> */
private array $f = [123 => 123];
/** @var array<value-of<array<int, string>>, int> */
private array $g = ["test" => 123];
Expand All @@ -173,7 +173,7 @@ public function test(bool $v): array {
return $v ? ["a" => 123] : [123 => 123];
}
}
/** @var b<"testKey", "testValue", array<"testKey", "testValue">, b, class-string<b>, true> */
$b = new b;
$b->d["testKey"] = 123;
Expand All @@ -183,6 +183,19 @@ public function test(bool $v): array {
//$b->e["b"] = 123;
',
],
'intStringKeyAsInt' => [
'code' => '<?php
$a = ["15" => "a"];
$b = ["15.7" => "a"];
// since this is_numeric in PHP 8 but will not be int key
$c = ["15 " => "a"];
',
'assertions' => [
'$a===' => "array{15: 'a'}",
'$b===' => "array{'15.7': 'a'}",
'$c===' => "array{'15 ': 'a'}",
],
],
];
}

Expand Down

0 comments on commit 69aa389

Please sign in to comment.