Skip to content

Commit 19d001b

Browse files
authored
feat: allow object to define how they are mapped to array (#532)
1 parent 92ccb7d commit 19d001b

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Tempest\Mapper\Mappers;
66

7+
use JsonSerializable;
78
use Tempest\Mapper\Mapper;
89
use Tempest\Mapper\MapTo;
910

@@ -16,6 +17,10 @@ public function canMap(mixed $from, mixed $to): bool
1617

1718
public function map(mixed $from, mixed $to): array
1819
{
20+
if ($from instanceof JsonSerializable) {
21+
return $from->jsonSerialize();
22+
}
23+
1924
return (array) $from;
2025
}
2126
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tests\Tempest\Integration\Mapper\Fixtures;
6+
7+
use JsonSerializable;
8+
use Tempest\Mapper\Strict;
9+
10+
#[Strict]
11+
final class ObjectWithJsonSerialize implements JsonSerializable
12+
{
13+
public function __construct(
14+
public string $a,
15+
public string $b,
16+
) {
17+
}
18+
19+
public function jsonSerialize(): array
20+
{
21+
return [
22+
'c' => $this->a,
23+
'd' => $this->b,
24+
];
25+
}
26+
}

tests/Integration/Mapper/Mappers/ObjectToArrayMapperTestCase.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Tempest\Mapper\MapTo;
99
use Tests\Tempest\Integration\FrameworkIntegrationTestCase;
1010
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectA;
11+
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectWithJsonSerialize;
1112

1213
/**
1314
* @internal
@@ -20,4 +21,11 @@ public function test_object_to_array(): void
2021

2122
$this->assertSame(['a' => 'a', 'b' => 'b'], $array);
2223
}
24+
25+
public function test_custom_to_array(): void
26+
{
27+
$array = map(new ObjectWithJsonSerialize('a', 'b'))->to(MapTo::ARRAY);
28+
29+
$this->assertSame(['c' => 'a', 'd' => 'b'], $array);
30+
}
2331
}

0 commit comments

Comments
 (0)