From 0b038e34273923e08ed2a403f7f1add79577f0dc Mon Sep 17 00:00:00 2001 From: Nikolay Novikov Date: Fri, 20 Sep 2024 13:58:40 +0300 Subject: [PATCH] patch --- src/Mapper.php | 2 +- tests/MapperTest.php | 31 +++++++++++++++++++++++++++++++ tests/Mappers/OptionalMapper.php | 20 ++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 tests/Mappers/OptionalMapper.php diff --git a/src/Mapper.php b/src/Mapper.php index 2991026..516f689 100644 --- a/src/Mapper.php +++ b/src/Mapper.php @@ -56,7 +56,7 @@ public static function from(array|object $data): static } } - if (is_array($value) && is_subclass_of($param->getType()->getName(), self::class)) { + if (is_array($value) && ! $param->getType() instanceof \ReflectionUnionType && is_subclass_of($param->getType()->getName(), self::class)) { $class = $param->getType()->getName(); $value = $class::from($value); } diff --git a/tests/MapperTest.php b/tests/MapperTest.php index a9b2663..2dc5a7f 100644 --- a/tests/MapperTest.php +++ b/tests/MapperTest.php @@ -12,6 +12,7 @@ use AnourValar\LaravelAtom\Tests\Mappers\ArrayOfMapper; use AnourValar\LaravelAtom\Tests\Mappers\ExcludeMapper; use AnourValar\LaravelAtom\Tests\Models\Post; +use AnourValar\LaravelAtom\Tests\Mappers\OptionalMapper; class MapperTest extends \Orchestra\Testbench\TestCase { @@ -187,6 +188,36 @@ public function test_arrayOf_exclude() ); } + /** + * @return void + */ + public function test_optional() + { + // Empty + $this->assertSame([], OptionalMapper::from([])->toArray()); + + // A + $this->assertSame(['a' => ['foo']], OptionalMapper::from(['a' => ['foo']])->toArray()); + + // B + $this->assertSame( + ['b' => [['a' => '1', 'b' => 2, 'c' => null, 'd' => 1]]], + OptionalMapper::from(['b' => [['a' => 1, 'b' => 2]]])->toArray() + ); + + // A + B + $this->assertSame( + [ + 'a' => ['foo'], + 'b' => [['a' => '1', 'b' => 2, 'c' => null, 'd' => 1], ['a' => '3', 'b' => 4, 'c' => '5', 'd' => 6], ['a' => '7', 'b' => 8, 'c' => null, 'd' => 1]], + ], + OptionalMapper::from([ + 'a' => ['foo'], + 'b' => [['a' => 1, 'b' => 2], SimpleMapper::from(['a' => 3, 'b' => 4, 'c' => 5, 'd' => 6]), new SimpleMapper(7, 8)], + ])->toArray() + ); + } + /** * @return void */ diff --git a/tests/Mappers/OptionalMapper.php b/tests/Mappers/OptionalMapper.php new file mode 100644 index 0000000..9f08fee --- /dev/null +++ b/tests/Mappers/OptionalMapper.php @@ -0,0 +1,20 @@ +