File tree Expand file tree Collapse file tree 2 files changed +33
-2
lines changed
Expand file tree Collapse file tree 2 files changed +33
-2
lines changed Original file line number Diff line number Diff line change 1313use Tempest \Mapper \Mappers \ObjectToArrayMapper ;
1414use Tempest \Mapper \Mappers \ObjectToJsonMapper ;
1515use Tempest \Reflection \FunctionReflector ;
16+ use Tempest \Support \Arr ;
1617use 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 )) {
Original file line number Diff line number Diff line change 1818use Tests \Tempest \Integration \Mapper \Fixtures \EnumToCast ;
1919use Tests \Tempest \Integration \Mapper \Fixtures \NestedObjectA ;
2020use Tests \Tempest \Integration \Mapper \Fixtures \NestedObjectB ;
21+ use Tests \Tempest \Integration \Mapper \Fixtures \ObjectA ;
2122use Tests \Tempest \Integration \Mapper \Fixtures \ObjectFactoryA ;
2223use Tests \Tempest \Integration \Mapper \Fixtures \ObjectThatShouldUseCasters ;
2324use 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}
You can’t perform that action at this time.
0 commit comments