Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/mapper/src/ObjectFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down Expand Up @@ -47,7 +48,7 @@ public function withData(mixed $data): self
{
$this->from = $data;

return $this;
return clone $this;
}

/**
Expand Down Expand Up @@ -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)) {
Expand Down
23 changes: 23 additions & 0 deletions tests/Integration/Mapper/MapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}
Loading