Skip to content

Commit 85575db

Browse files
committed
[TypeInfo] ArrayShape can resolve key type as callable instead of string
In PHP, array key type is either string or int. Although callable is not entirely false as long as it's a string callable, using callable as a key type for an array seems wrong, and it's unlikely to be what we expect. This is peculiarly true in environment when key name might collide with global function name. Proposed change is to check for int/string instead of resolving type. Because the input is an array, the key is already narrowed down to string|int in the input This bugfix is also a change of behavior, as callable was likely to be fed in keyTypes, and it won't longer occur with that change.
1 parent 7f69f34 commit 85575db

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,12 @@ public function testCreateArrayShape()
226226
), Type::arrayShape(['foo' => Type::bool()], extraKeyType: Type::string(), extraValueType: Type::bool()));
227227
}
228228

229+
public function testCreateArrayShapeWithCallableKey()
230+
{
231+
$arrayShape = new ArrayShapeType(['substr' => ['type' => Type::string(), 'optional' => false]]);
232+
$this->assertEquals(Type::string(), $arrayShape->getCollectionKeyType());
233+
}
234+
229235
public function testCreateArrayKey()
230236
{
231237
$this->assertEquals(new UnionType(Type::int(), Type::string()), Type::arrayKey());

src/Symfony/Component/TypeInfo/Type/ArrayShapeType.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,11 @@ public function __construct(
4141
$valueTypes = [];
4242

4343
foreach ($shape as $k => $v) {
44-
$keyTypes[] = self::fromValue($k);
44+
if (\is_int($k)) {
45+
$keyTypes[] = Type::int();
46+
} else {
47+
$keyTypes[] = Type::string();
48+
}
4549
$valueTypes[] = $v['type'];
4650
}
4751

0 commit comments

Comments
 (0)