Skip to content
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

feat: support unions in arrays #1552

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
47 changes: 40 additions & 7 deletions src/Metadata/Driver/DocBlockDriver/DocBlockTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
use PHPStan\PhpDocParser\Parser\TypeParser;
use PHPStan\PhpDocParser\ParserConfig;

use function sprintf;

/**
* @internal
*/
Expand Down Expand Up @@ -131,19 +133,50 @@ private function getDocBlocTypeHint($reflector): ?string

// Generic array syntax: array<Product> | array<\Foo\Bar\Product> | array<int,Product>
if ($type instanceof GenericTypeNode) {
if ($this->isSimpleType($type->type, 'array')) {
$resolvedTypes = array_map(fn (TypeNode $node) => $this->resolveTypeFromTypeNode($node, $reflector), $type->genericTypes);
$isSimpleTypeArray = $this->isSimpleType($type->type, 'array');
$isSimpleTypeList = $this->isSimpleType($type->type, 'list');
if (!$isSimpleTypeArray && !$isSimpleTypeList) {
throw new \InvalidArgumentException(sprintf("Can't use non-array generic type %s for collection in %s:%s", (string) $type->type, $reflector->getDeclaringClass()->getName(), $reflector->getName()));
}

if ($isSimpleTypeList) {
$keyType = 'int';
$valuesIndex = 0;
} else {
if (1 === count($type->genericTypes)) {
$keyType = null;
$valuesIndex = 0;
} else {
$keyType = $this->resolveTypeFromTypeNode($type->genericTypes[0], $reflector);
$valuesIndex = 1;
}
}

if ($type->genericTypes[$valuesIndex] instanceof UnionTypeNode) {
$valueTypes = array_map(
function (TypeNode $node) use ($reflector) {
if ($node instanceof ArrayTypeNode) {
$resolvedType = $this->resolveTypeFromTypeNode($node->type, $reflector);

return 'array<' . implode(',', $resolvedTypes) . '>';
return 'array<' . $resolvedType . '>';
}

return $this->resolveTypeFromTypeNode($node, $reflector);
},
$type->genericTypes[$valuesIndex]->types,
);
} else {
$valueType = $this->resolveTypeFromTypeNode($type->genericTypes[$valuesIndex], $reflector);
$valueTypes = [$valueType];
}

if ($this->isSimpleType($type->type, 'list')) {
$resolvedTypes = array_map(fn (TypeNode $node) => $this->resolveTypeFromTypeNode($node, $reflector), $type->genericTypes);
$valueType = implode('|', $valueTypes);

return 'array<int, ' . implode(',', $resolvedTypes) . '>';
if (null === $keyType) {
return sprintf('array<%s>', $valueType);
}

throw new \InvalidArgumentException(sprintf("Can't use non-array generic type %s for collection in %s:%s", (string) $type->type, $reflector->getDeclaringClass()->getName(), $reflector->getName()));
return sprintf('array<%s, %s>', $keyType, $valueType);
}

// Primitives and class names: Collection | \Foo\Bar\Product | string
Expand Down
4 changes: 4 additions & 0 deletions src/Type/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ final class Lexer extends AbstractLexer
public const T_TYPE_END = 8;
public const T_IDENTIFIER = 9;
public const T_NULL = 10;
public const T_UNION_SEPARATOR = 11;

public function parse(string $type)
{
Expand Down Expand Up @@ -103,6 +104,9 @@ protected function getType(&$value)
case '[' === $value:
return self::T_ARRAY_START;

case '|' === $value:
return self::T_UNION_SEPARATOR;

// Default
default:
// Do nothing
Expand Down
6 changes: 6 additions & 0 deletions src/Type/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ private function visitCompoundType(): array
break;
}

if ($this->lexer->isNextToken(Lexer::T_UNION_SEPARATOR)) {
$this->match(Lexer::T_UNION_SEPARATOR);

continue;
}

$this->match(Lexer::T_COMMA);
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/Fixtures/DocBlockType/Collection/MapTypedAsGenericClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,19 @@ class MapTypedAsGenericClass
* @var array<int, Product>
*/
public array $productIds;

/**
* @var array<Product|Vehicle>
*/
public array $productOrVehicleIds;

/**
* @var array<int, Product|Vehicle>
*/
public array $productOrVehicleIdsWithKey;

/**
* @var array<Product|Vehicle[]>
*/
public array $productOrVehicles;
}
31 changes: 31 additions & 0 deletions tests/Metadata/Driver/DocBlockDriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,37 @@ public function testInferDocBlockMapFromGenericLikeClass()
['name' => 'array', 'params' => [['name' => 'int', 'params' => []], ['name' => Product::class, 'params' => []]]],
$m->propertyMetadata['productIds']->type,
);
self::assertEquals(
[
'name' => 'array',
'params' => [
['name' => Product::class, 'params' => []],
['name' => Vehicle::class, 'params' => []],
],
],
$m->propertyMetadata['productOrVehicleIds']->type,
);
self::assertEquals(
[
'name' => 'array',
'params' => [
['name' => 'int', 'params' => []],
['name' => Product::class, 'params' => []],
['name' => Vehicle::class, 'params' => []],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@simPod It seems like array<int, string> and array<int|string> will create exactly the same metadata 😓 I would consider using Union pseudo type same as for the unions, so it will be handled by the Union Handler :D

],
],
$m->propertyMetadata['productOrVehicleIdsWithKey']->type,
);
self::assertEquals(
[
'name' => 'array',
'params' => [
['name' => Product::class, 'params' => []],
['name' => 'array', 'params' => [['name' => Vehicle::class, 'params' => []]]],
],
],
$m->propertyMetadata['productOrVehicles']->type,
);
}

public function testInferDocBlockCollectionOfClassesIgnoringNullTypeHint()
Expand Down
Loading