Skip to content

Commit

Permalink
Fix union scalar with object not supported
Browse files Browse the repository at this point in the history
  • Loading branch information
vdauchy committed Dec 16, 2023
1 parent e384ad6 commit 9c2057f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/Mapper/Tree/Builder/UnionNodeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,13 @@ private function narrow(UnionType $type, mixed $source): Type

private function tryToBuildClassNode(UnionType $type, Shell $shell, RootNodeBuilder $rootBuilder): ?TreeNode
{
$classTypes = [];
$classTypes = array_filter(
$type->types(),
fn (Type $type) => $type instanceof ClassType,
);

foreach ($type->types() as $subType) {
if ($subType instanceof NullType) {
continue;
}

if (! $subType instanceof ClassType) {
return null;
}

$classTypes[] = $subType;
if (count($classTypes) === 0) {
return null;
}

$objectBuilder = $this->objectBuilder($shell->value(), ...$classTypes);
Expand Down
21 changes: 21 additions & 0 deletions tests/Integration/Mapping/Object/UnionOfObjectsMappingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,27 @@ public function test_mapping_to_union_of_null_and_objects_can_infer_object(): vo
self::assertSame('fiz', $result->fiz);
}

public function test_mapping_to_union_of_string_and_object_can_infer_object(): void
{
try {
$result = (new MapperBuilder())
->mapper()
->map(
'string|' . SomeObjectWithBazAndFiz::class,
[
'baz' => 'baz',
'fiz' => 'fiz',
]
);
} catch (MappingError $error) {
$this->mappingFail($error);
}

self::assertInstanceOf(SomeObjectWithBazAndFiz::class, $result);
self::assertSame('baz', $result->baz);
self::assertSame('fiz', $result->fiz);
}

/**
*
* @dataProvider mapping_error_when_cannot_resolve_union_data_provider
Expand Down

0 comments on commit 9c2057f

Please sign in to comment.