Union of scalar and array of classes does not work
JanMikes opened this issue · comments
Jan Mikeš commented
Hi, when trying to map union of scalar and array of classes, i get error:
CuyZ\Valinor\Mapper\TypeTreeMapperError: Could not map type `Foo`. An error occurred at path items: Invalid value array{0: array{…}}.
(new MapperBuilder())->mapper()->map(Foo::class, Source::array([
'items' => [
[
'id' => 1,
'value' => 'baz',
],
],
]));
readonly final class Foo
{
public function __construct(
/** @var string|list<Bar> */
public string|array $items,
) {
}
}
readonly final class Bar
{
public function __construct(
public int $id,
public string $value,
) {
}
}
When trying as source the string value (first type of the union) it works as expected.
(new MapperBuilder())->mapper()->map(Foo::class, Source::array([
'items' => 'some value',
]));
Currently my workaround is to not map it to array of objects but to union of string and array shape and do the mapping later separately which works but it is not as comfortable as it could be.
Jano Paetzold commented
Similar issue with something like ''|DateTimeImmutable
(for an API that returns date strings or empty strings): Will not map the dates appropriately (probably because they are not ''
).