Skip to content

Commit 0b824b6

Browse files
authored
fix(mapper): properly serialize nullable properties in objects (#1107)
1 parent 9d86d13 commit 0b824b6

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

src/Tempest/Mapper/src/Mappers/ObjectToArrayMapper.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ private function resolvePropertyValue(PropertyReflector $property, object $objec
4545
{
4646
$propertyValue = $property->getValue($object);
4747

48-
if (($serializer = $this->serializerFactory->forProperty($property)) !== null) {
48+
if ($propertyValue !== null && ($serializer = $this->serializerFactory->forProperty($property)) !== null) {
4949
return $serializer->serialize($propertyValue);
5050
}
5151

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests\Tempest\Integration\Mapper\Fixtures;
6+
7+
use DateTimeImmutable;
8+
use Tempest\Mapper\Strict;
9+
10+
#[Strict]
11+
final class ObjectWithNullableProperties
12+
{
13+
public function __construct(
14+
public string $a,
15+
public float $b,
16+
public ?DateTimeImmutable $c,
17+
) {}
18+
}

tests/Integration/Mapper/Mappers/ObjectToArrayMapperTestCase.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@
77
use Tests\Tempest\Integration\FrameworkIntegrationTestCase;
88
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectA;
99
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectWithJsonSerialize;
10+
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectWithNullableProperties;
1011

1112
use function Tempest\map;
1213

1314
/**
15+
*
1416
* @internal
1517
*/
1618
final class ObjectToArrayMapperTestCase extends FrameworkIntegrationTestCase
@@ -28,4 +30,19 @@ public function test_custom_to_array(): void
2830

2931
$this->assertSame(['c' => 'a', 'd' => 'b'], $array);
3032
}
33+
34+
public function test_object_with_nullable_properties_to_array(): void
35+
{
36+
$object = new ObjectWithNullableProperties(a: 'a', b: 3.1416, c: null);
37+
$array = map($object)->toArray();
38+
39+
$this->assertSame(
40+
[
41+
'a' => 'a',
42+
'b' => '3.1416',
43+
'c' => null,
44+
],
45+
$array,
46+
);
47+
}
3148
}

0 commit comments

Comments
 (0)