Skip to content

Commit

Permalink
patch
Browse files Browse the repository at this point in the history
  • Loading branch information
AnourValar committed Sep 20, 2024
1 parent 3519e59 commit 0b038e3
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
31 changes: 31 additions & 0 deletions tests/MapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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
*/
Expand Down
20 changes: 20 additions & 0 deletions tests/Mappers/OptionalMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace AnourValar\LaravelAtom\Tests\Mappers;

use AnourValar\LaravelAtom\Mapper;
use AnourValar\LaravelAtom\Mapper\ArrayOf;
use AnourValar\LaravelAtom\Mapper\Mapping;
use AnourValar\LaravelAtom\Mapper\MappingSnakeCase;
use AnourValar\LaravelAtom\Mapper\Optional;

class OptionalMapper extends Mapper
{
public function __construct(
public array|Optional $a,
#[ArrayOf(SimpleMapper::class)]
public array|Optional $b,
) {

}
}

0 comments on commit 0b038e3

Please sign in to comment.