Skip to content

Commit

Permalink
fix: properly handle union of null and objects
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Feb 12, 2023
1 parent dc7f5c3 commit 8f03a7e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
4 changes: 4 additions & 0 deletions src/Mapper/Tree/Builder/UnionNodeBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ private function tryToBuildClassNode(UnionType $type, Shell $shell, RootNodeBuil
$classTypes = [];

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

if (! $subType instanceof ClassType) {
return null;
}
Expand Down
46 changes: 38 additions & 8 deletions tests/Integration/Mapping/Object/UnionOfObjectsMappingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ public function test_objects_sharing_one_property_are_resolved_correctly(): void
->registerConstructor([SomeFooAndBarObject::class, 'constructorB'])
->mapper()
->map(UnionOfFooAndBarAndFoo::class, [
'foo',
['foo' => 'foo', 'bar' => 'bar'],
]);
'foo',
['foo' => 'foo', 'bar' => 'bar'],
]);
} catch (MappingError $error) {
$this->mappingFail($error);
}
Expand All @@ -30,6 +30,27 @@ public function test_objects_sharing_one_property_are_resolved_correctly(): void
self::assertInstanceOf(SomeFooAndBarObject::class, $result->objects[1]);
}

public function test_mapping_to_union_of_null_and_objects_can_infer_object(): void
{
try {
$result = (new MapperBuilder())
->mapper()
->map(
'null|' . SomeObjectWithFooAndBar::class . '|' . 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 Expand Up @@ -63,11 +84,6 @@ public function mapping_error_when_cannot_resolve_union_data_provider(): iterabl
}
}

final class NativeUnionOfObjects
{
public SomeFooObject|SomeBarObject $object;
}

// PHP8.1 Readonly properties
final class UnionOfFooAndBar
{
Expand Down Expand Up @@ -133,3 +149,17 @@ public static function constructorB(string $foo, string $bar): self
return new self($foo, $bar, 'default baz');
}
}

final class SomeObjectWithFooAndBar
{
public string $foo;

public string $bar;
}

final class SomeObjectWithBazAndFiz
{
public string $baz;

public string $fiz;
}

0 comments on commit 8f03a7e

Please sign in to comment.