Skip to content

Commit accab81

Browse files
authored
feat(mapper): support converting array of objects to array (#1523)
1 parent 122d7a3 commit accab81

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

packages/mapper/src/ObjectFactory.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Tempest\Mapper\Mappers\ObjectToArrayMapper;
1414
use Tempest\Mapper\Mappers\ObjectToJsonMapper;
1515
use Tempest\Reflection\FunctionReflector;
16+
use Tempest\Support\Arr;
1617
use Tempest\Support\Json;
1718

1819
/** @template ClassType */
@@ -47,7 +48,7 @@ public function withData(mixed $data): self
4748
{
4849
$this->from = $data;
4950

50-
return $this;
51+
return clone $this;
5152
}
5253

5354
/**
@@ -124,7 +125,14 @@ public function toArray(): array
124125
}
125126

126127
if (is_array($this->from)) {
127-
return $this->from;
128+
if (! $this->isCollection) {
129+
return $this->from;
130+
}
131+
132+
return Arr\map_with_keys(
133+
array: $this->from,
134+
map: fn (mixed $item, mixed $key) => yield $key => $this->withData($item)->toArray(),
135+
);
128136
}
129137

130138
if (Json\is_valid($this->from)) {

tests/Integration/Mapper/MapperTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Tests\Tempest\Integration\Mapper\Fixtures\EnumToCast;
1919
use Tests\Tempest\Integration\Mapper\Fixtures\NestedObjectA;
2020
use Tests\Tempest\Integration\Mapper\Fixtures\NestedObjectB;
21+
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectA;
2122
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectFactoryA;
2223
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectThatShouldUseCasters;
2324
use Tests\Tempest\Integration\Mapper\Fixtures\ObjectWithMapFromAttribute;
@@ -356,4 +357,26 @@ public function test_nested_object_to_array_casting(): void
356357
],
357358
], $array);
358359
}
360+
361+
public function test_array_of_objects_to_array(): void
362+
{
363+
$objects = [
364+
new ObjectA('a', 'b'),
365+
new ObjectA('c', 'd'),
366+
new NestedObjectA(
367+
items: [
368+
new NestedObjectB('a'),
369+
new NestedObjectB('b'),
370+
],
371+
),
372+
];
373+
374+
$array = map($objects)->collection()->toArray();
375+
376+
$this->assertSame([
377+
['a' => 'a', 'b' => 'b'],
378+
['a' => 'c', 'b' => 'd'],
379+
['items' => [['name' => 'a'], ['name' => 'b']]],
380+
], $array);
381+
}
359382
}

0 commit comments

Comments
 (0)