Skip to content

Fix compound array key support #188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/TypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -551,13 +551,24 @@ private function createArray(array $typeNodes, Context $context): Array_
return new Array_(...$types);
}

if ($types[1] instanceof String_ || $types[1] instanceof Integer || $types[1] instanceof ArrayKey) {
if ($this->validArrayKeyType($types[1]) || $types[1] instanceof ArrayKey) {
return new Array_(...$types);
}

if ($types[1] instanceof Compound && $types[1]->getIterator()->count() === 2) {
if ($this->validArrayKeyType($types[1]->get(0)) && $this->validArrayKeyType($types[1]->get(1))) {
return new Array_(...$types);
}
}

throw new RuntimeException('An array can have only integers or strings as keys');
}

private function validArrayKeyType(?Type $type): bool
{
return $type instanceof String_ || $type instanceof Integer;
}

private function parse(TokenIterator $tokenIterator): TypeNode
{
try {
Expand Down
12 changes: 12 additions & 0 deletions tests/unit/TypeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,18 @@ public function genericsProvider(): array
new Integer()
),
],
[
'array<string|int, Foo\\Bar>',
new Array_(
new Object_(new Fqsen('\\phpDocumentor\\Foo\\Bar')),
new Compound(
[
new String_(),
new Integer(),
]
)
),
],
[
'Collection<array-key, int>[]',
new Array_(
Expand Down