From a5f779ca417619d9cd598cba46638b64cd3e6c77 Mon Sep 17 00:00:00 2001 From: Mathias Arlaud Date: Thu, 20 Feb 2025 12:25:33 +0100 Subject: [PATCH] [TypeInfo] Fix create union with nullable type --- src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php | 4 ++++ src/Symfony/Component/TypeInfo/TypeFactoryTrait.php | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php b/src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php index 60a0ded22c648..50a6f5a2e6449 100644 --- a/src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php +++ b/src/Symfony/Component/TypeInfo/Tests/TypeFactoryTest.php @@ -205,5 +205,9 @@ public function testCreateNullable() new NullableType(new UnionType(new BuiltinType(TypeIdentifier::INT), new BuiltinType(TypeIdentifier::STRING))), Type::nullable(Type::union(Type::int(), Type::string(), Type::null())), ); + $this->assertEquals( + new NullableType(new UnionType(new BuiltinType(TypeIdentifier::INT), new BuiltinType(TypeIdentifier::STRING))), + Type::union(Type::nullable(Type::int()), Type::string()), + ); } } diff --git a/src/Symfony/Component/TypeInfo/TypeFactoryTrait.php b/src/Symfony/Component/TypeInfo/TypeFactoryTrait.php index d32a97276057c..b8e15f209fa00 100644 --- a/src/Symfony/Component/TypeInfo/TypeFactoryTrait.php +++ b/src/Symfony/Component/TypeInfo/TypeFactoryTrait.php @@ -266,6 +266,13 @@ public static function union(Type ...$types): UnionType $isNullable = fn (Type $type): bool => $type instanceof BuiltinType && TypeIdentifier::NULL === $type->getTypeIdentifier(); foreach ($types as $type) { + if ($type instanceof NullableType) { + $nullableUnion = true; + $unionTypes[] = $type->getWrappedType(); + + continue; + } + if ($type instanceof UnionType) { foreach ($type->getTypes() as $unionType) { if ($isNullable($type)) {