Skip to content

Commit

Permalink
Fix marshalling/unmarshalling of nullable object properties (#334)
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk authored Jul 20, 2023
1 parent 479b0b4 commit cf2f921
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Internal/Marshaller/Type/ObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,13 @@ public static function makeRule(\ReflectionProperty $property): ?MarshallingRule
return null;
}

return new MarshallingRule($property->getName(), self::class, $type->getName());
return $type->allowsNull()
? new MarshallingRule(
$property->getName(),
NullableType::class,
new MarshallingRule(type: self::class, of: $type->getName()),
)
: new MarshallingRule($property->getName(), self::class, $type->getName());
}

/**
Expand Down
19 changes: 19 additions & 0 deletions tests/Unit/DTO/Type/ObjectType/ObjectTypeTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Temporal\Tests\Unit\DTO\Type\ObjectType\Stub\Nested2;
use Temporal\Tests\Unit\DTO\Type\ObjectType\Stub\Nested3;
use Temporal\Tests\Unit\DTO\Type\ObjectType\Stub\NestedParent;
use Temporal\Tests\Unit\DTO\Type\ObjectType\Stub\NullableProperty;
use Temporal\Tests\Unit\DTO\Type\ObjectType\Stub\ParentDto;
use Temporal\Tests\Unit\DTO\DTOMarshallingTestCase;
use Temporal\Tests\Unit\DTO\Type\ObjectType\Stub\ReadonlyProperty;
Expand Down Expand Up @@ -60,6 +61,24 @@ public function testReadonlyMarshal(): void
$this->assertEquals(['child' => ['foo' => 'foo']], $result);
}

public function testNullableObjectMarshal(): void
{
$dto = new NullableProperty(null);

$result = $this->marshal($dto);

$this->assertEquals(['child' => null], $result);
}

public function testNullableObjectUnmarshal(): void
{
$dto = $this->unmarshal([
'child' => null,
], (new ReflectionClass(NullableProperty::class))->newInstanceWithoutConstructor());

self::assertEquals(new NullableProperty(null), $dto);
}

/**
* @requires PHP >= 8.1
*/
Expand Down
20 changes: 20 additions & 0 deletions tests/Unit/DTO/Type/ObjectType/Stub/NullableProperty.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/**
* This file is part of Temporal package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Temporal\Tests\Unit\DTO\Type\ObjectType\Stub;

final class NullableProperty
{
public function __construct(
public ?ChildDto $child,
) {
}
}

0 comments on commit cf2f921

Please sign in to comment.