-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionCaster.php
More file actions
38 lines (28 loc) · 1.02 KB
/
CollectionCaster.php
File metadata and controls
38 lines (28 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
declare(strict_types=1);
namespace TinyBlocks\Mapper\Internal\Mappers\Object\Casters;
use TinyBlocks\Collection\Collectible;
use TinyBlocks\Mapper\Internal\Mappers\Object\ObjectMapper;
use TinyBlocks\Mapper\Internal\Mappers\Object\Reflector;
use TinyBlocks\Mapper\IterableMapper;
final readonly class CollectionCaster implements Caster
{
public function __construct(private string $class)
{
}
public function castValue(mixed $value): Collectible
{
$reflectionClass = Reflector::reflectFrom(class: $this->class);
/** @var IterableMapper & Collectible $instance */
$instance = $reflectionClass->newInstanceWithoutConstructor();
$type = $instance->getType();
if ($type === $this->class) {
return $instance->createFrom(elements: $value);
}
$mapped = [];
foreach ($value as $item) {
$mapped[] = new ObjectMapper()->map(iterable: $item, class: $type);
}
return $instance->createFrom(elements: $mapped);
}
}