Skip to content

Commit

Permalink
feat: allow object to define how they are mapped to array (#532)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeroen-G authored Oct 4, 2024
1 parent 92ccb7d commit 19d001b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Tempest/Mapper/src/Mappers/ObjectToArrayMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Tempest\Mapper\Mappers;

use JsonSerializable;
use Tempest\Mapper\Mapper;
use Tempest\Mapper\MapTo;

Expand All @@ -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;
}
}
26 changes: 26 additions & 0 deletions tests/Integration/Mapper/Fixtures/ObjectWithJsonSerialize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Tests\Tempest\Integration\Mapper\Fixtures;

use JsonSerializable;
use Tempest\Mapper\Strict;

#[Strict]
final class ObjectWithJsonSerialize implements JsonSerializable
{
public function __construct(
public string $a,
public string $b,
) {
}

public function jsonSerialize(): array
{
return [
'c' => $this->a,
'd' => $this->b,
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}
}

0 comments on commit 19d001b

Please sign in to comment.