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

Fix parsing of class string of unions #8834

Merged
merged 1 commit into from Dec 4, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 7 additions & 8 deletions src/Psalm/Internal/Type/TypeParser.php
Expand Up @@ -711,17 +711,16 @@ private static function getTypeFromGenericTree(
);
}

$param_union_types = array_values($generic_params[0]->getAtomicTypes());

if (count($param_union_types) > 1) {
throw new TypeParseTreeException('Union types are not allowed in class string param');
}
$types = [];
foreach ($generic_params[0]->getAtomicTypes() as $type) {
if (!$type instanceof TNamedObject) {
throw new TypeParseTreeException('Class string param should be a named object');
}

if (!$param_union_types[0] instanceof TNamedObject) {
throw new TypeParseTreeException('Class string param should be a named object');
$types []= new TClassString($type->value, $type, false, false, false, $from_docblock);
}

return new TClassString($class_name, $param_union_types[0], false, false, false, $from_docblock);
return new Union($types);
}

if ($generic_type_value === 'class-string-map') {
Expand Down
20 changes: 20 additions & 0 deletions tests/ClassLikeStringTest.php
Expand Up @@ -859,6 +859,26 @@ function foo(A $a): void {
if (get_class($a) === A::class) {}
}',
],
'classStringUnion' => [
'code' => '<?php
class Foo
{
/** @var class-string<TypeOne>|class-string<TypeTwo> */
public ?string $bar = null;
/** @var class-string<TypeOne|TypeTwo> */
public ?string $baz = null;
}

class TypeOne {}

class TypeTwo {}

$foo = new Foo;
$foo->bar = TypeOne::class;
$foo->bar = TypeOne::class;
$foo->baz = TypeTwo::class;
$foo->baz = TypeTwo::class;'
]
];
}

Expand Down