-
-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathObjectToArrayMapper.php
More file actions
92 lines (71 loc) · 2.43 KB
/
ObjectToArrayMapper.php
File metadata and controls
92 lines (71 loc) · 2.43 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace Tempest\Mapper\Mappers;
use JsonSerializable;
use Tempest\Mapper\Context;
use Tempest\Mapper\Hidden;
use Tempest\Mapper\Mapper;
use Tempest\Mapper\MapTo;
use Tempest\Mapper\SerializerFactory;
use Tempest\Reflection\ClassReflector;
use Tempest\Reflection\PropertyReflector;
use function Tempest\Mapper\map;
final readonly class ObjectToArrayMapper implements Mapper
{
public function __construct(
private SerializerFactory $serializerFactory,
private Context $context,
) {}
public function canMap(mixed $from, mixed $to): bool
{
return false;
}
public function map(mixed $from, mixed $to): mixed
{
if ($from instanceof JsonSerializable) {
return $from->jsonSerialize();
}
if (is_object($from)) {
$class = new ClassReflector($from);
$mappedProperties = [];
foreach ($class->getPublicProperties() as $property) {
if ($property->hasAttribute(Hidden::class)) {
continue;
}
$propertyName = $this->resolvePropertyName($property);
$propertyValue = $this->resolvePropertyValue($property, $from);
$mappedProperties[$propertyName] = $propertyValue;
}
} else {
$mappedProperties = $from;
}
return $mappedProperties;
}
private function resolvePropertyValue(PropertyReflector $property, object $object): mixed
{
if (! $property->isInitialized($object)) {
return null;
}
$propertyValue = $property->getValue($object);
if ($property->getIterableType()?->isClass()) {
foreach ($propertyValue as $key => $value) {
if (is_object($value)) {
$propertyValue[$key] = map($value)->toArray();
}
}
return $propertyValue;
}
if ($propertyValue !== null && ($serializer = $this->serializerFactory->in($this->context)->forProperty($property)) !== null) {
return $serializer->serialize($propertyValue);
}
return $propertyValue;
}
private function resolvePropertyName(PropertyReflector $property): string
{
$mapTo = $property->getAttribute(MapTo::class);
if ($mapTo !== null) {
return $mapTo->name;
}
return $property->getName();
}
}