From 19d001bde2fbb2b2433fb6c4aebf6b538dfb8fb0 Mon Sep 17 00:00:00 2001 From: JeroenG Date: Fri, 4 Oct 2024 06:15:27 +0200 Subject: [PATCH] feat: allow object to define how they are mapped to array (#532) --- .../src/Mappers/ObjectToArrayMapper.php | 5 ++++ .../Fixtures/ObjectWithJsonSerialize.php | 26 +++++++++++++++++++ .../Mappers/ObjectToArrayMapperTestCase.php | 8 ++++++ 3 files changed, 39 insertions(+) create mode 100644 tests/Integration/Mapper/Fixtures/ObjectWithJsonSerialize.php diff --git a/src/Tempest/Mapper/src/Mappers/ObjectToArrayMapper.php b/src/Tempest/Mapper/src/Mappers/ObjectToArrayMapper.php index 74608e421..c2f683e60 100644 --- a/src/Tempest/Mapper/src/Mappers/ObjectToArrayMapper.php +++ b/src/Tempest/Mapper/src/Mappers/ObjectToArrayMapper.php @@ -4,6 +4,7 @@ namespace Tempest\Mapper\Mappers; +use JsonSerializable; use Tempest\Mapper\Mapper; use Tempest\Mapper\MapTo; @@ -16,6 +17,10 @@ public function canMap(mixed $from, mixed $to): bool public function map(mixed $from, mixed $to): array { + if ($from instanceof JsonSerializable) { + return $from->jsonSerialize(); + } + return (array) $from; } } diff --git a/tests/Integration/Mapper/Fixtures/ObjectWithJsonSerialize.php b/tests/Integration/Mapper/Fixtures/ObjectWithJsonSerialize.php new file mode 100644 index 000000000..84a792a82 --- /dev/null +++ b/tests/Integration/Mapper/Fixtures/ObjectWithJsonSerialize.php @@ -0,0 +1,26 @@ + $this->a, + 'd' => $this->b, + ]; + } +} diff --git a/tests/Integration/Mapper/Mappers/ObjectToArrayMapperTestCase.php b/tests/Integration/Mapper/Mappers/ObjectToArrayMapperTestCase.php index 2bc7dfe5c..eab3f67c7 100644 --- a/tests/Integration/Mapper/Mappers/ObjectToArrayMapperTestCase.php +++ b/tests/Integration/Mapper/Mappers/ObjectToArrayMapperTestCase.php @@ -8,6 +8,7 @@ use Tempest\Mapper\MapTo; use Tests\Tempest\Integration\FrameworkIntegrationTestCase; use Tests\Tempest\Integration\Mapper\Fixtures\ObjectA; +use Tests\Tempest\Integration\Mapper\Fixtures\ObjectWithJsonSerialize; /** * @internal @@ -20,4 +21,11 @@ public function test_object_to_array(): void $this->assertSame(['a' => 'a', 'b' => 'b'], $array); } + + public function test_custom_to_array(): void + { + $array = map(new ObjectWithJsonSerialize('a', 'b'))->to(MapTo::ARRAY); + + $this->assertSame(['c' => 'a', 'd' => 'b'], $array); + } }