diff --git a/packages/mapper/src/ObjectFactory.php b/packages/mapper/src/ObjectFactory.php index e1fd5e663..eec40d67a 100644 --- a/packages/mapper/src/ObjectFactory.php +++ b/packages/mapper/src/ObjectFactory.php @@ -13,6 +13,7 @@ use Tempest\Mapper\Mappers\ObjectToArrayMapper; use Tempest\Mapper\Mappers\ObjectToJsonMapper; use Tempest\Reflection\FunctionReflector; +use Tempest\Support\Arr; use Tempest\Support\Json; /** @template ClassType */ @@ -47,7 +48,7 @@ public function withData(mixed $data): self { $this->from = $data; - return $this; + return clone $this; } /** @@ -124,7 +125,14 @@ public function toArray(): array } if (is_array($this->from)) { - return $this->from; + if (! $this->isCollection) { + return $this->from; + } + + return Arr\map_with_keys( + array: $this->from, + map: fn (mixed $item, mixed $key) => yield $key => $this->withData($item)->toArray(), + ); } if (Json\is_valid($this->from)) { diff --git a/tests/Integration/Mapper/MapperTest.php b/tests/Integration/Mapper/MapperTest.php index 9f49c4769..841615db4 100644 --- a/tests/Integration/Mapper/MapperTest.php +++ b/tests/Integration/Mapper/MapperTest.php @@ -18,6 +18,7 @@ use Tests\Tempest\Integration\Mapper\Fixtures\EnumToCast; use Tests\Tempest\Integration\Mapper\Fixtures\NestedObjectA; use Tests\Tempest\Integration\Mapper\Fixtures\NestedObjectB; +use Tests\Tempest\Integration\Mapper\Fixtures\ObjectA; use Tests\Tempest\Integration\Mapper\Fixtures\ObjectFactoryA; use Tests\Tempest\Integration\Mapper\Fixtures\ObjectThatShouldUseCasters; use Tests\Tempest\Integration\Mapper\Fixtures\ObjectWithMapFromAttribute; @@ -356,4 +357,26 @@ public function test_nested_object_to_array_casting(): void ], ], $array); } + + public function test_array_of_objects_to_array(): void + { + $objects = [ + new ObjectA('a', 'b'), + new ObjectA('c', 'd'), + new NestedObjectA( + items: [ + new NestedObjectB('a'), + new NestedObjectB('b'), + ], + ), + ]; + + $array = map($objects)->collection()->toArray(); + + $this->assertSame([ + ['a' => 'a', 'b' => 'b'], + ['a' => 'c', 'b' => 'd'], + ['items' => [['name' => 'a'], ['name' => 'b']]], + ], $array); + } }