/
NestedArrayMapper.php
115 lines (99 loc) · 3.12 KB
/
NestedArrayMapper.php
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
/**
* Created for DjinORM.
* Datetime: 10.11.2017 15:17
* @author Timur Kasumov aka XAKEPEHOK
*/
namespace DjinORM\Djin\Hydrator\Mappers;
use DjinORM\Djin\Exceptions\ExtractorException;
use DjinORM\Djin\Exceptions\HydratorException;
use DjinORM\Djin\Helpers\RepoHelper;
use DjinORM\Djin\Hydrator\Hydrator;
class NestedArrayMapper extends AbstractMapper implements ArrayMapperInterface, NestedMapperInterface
{
/**
* @var Hydrator
*/
protected $nestedMapper;
/**
* @var bool
*/
protected $allowNullNested;
public function __construct(
string $property,
string $classname,
array $mappers,
bool $allowNull = false
)
{
$this->property = $property;
$this->nestedMapper = new Hydrator($classname, $mappers);
$this->allowNull = $allowNull;
}
/**
* @param array $data
* @param object $object
* @return array|null
* @throws HydratorException
* @throws \ReflectionException
*/
public function hydrate(array $data, object $object): ?array
{
$property = $this->getProperty();
if (!isset($data[$property]) || $data[$property] === '') {
if ($this->isNullAllowed()) {
RepoHelper::setProperty($object, $this->getProperty(), null);
return null;
}
throw $this->nullHydratorException('array', $object);
}
$array = array_map(function ($data) use ($object) {
if (null === $data) {
if ($this->isNullAllowed()) {
return null;
}
return new HydratorException("Null instead of nested object is not allowed in " . $this->getDescription($object));
}
return $this->nestedMapper->hydrate($data);
}, $data[$property]);
RepoHelper::setProperty($object, $this->getProperty(), $array);
return $array;
}
/**
* @param object $object
* @return array
* @throws ExtractorException
* @throws \ReflectionException
*/
public function extract(object $object): array
{
$array = RepoHelper::getProperty($object, $this->getProperty());
if (!is_array($array) && !is_a($array, \ArrayAccess::class)) {
if ($this->isNullAllowed() == false) {
throw $this->nullExtractorException('array', $object);
}
return [
$this->getProperty() => null
];
}
$array = array_map(function ($nestedObject) use ($object) {
if (null === $nestedObject) {
if ($this->isNullAllowed()) {
return null;
}
new ExtractorException("Impossible to save null instead of nested object from " . $this->getDescription($object));
}
return $this->nestedMapper->extract($nestedObject);
}, $array);
return [
$this->getProperty() => $array
];
}
/**
* @return Hydrator
*/
public function getNestedMappersHandler(): Hydrator
{
return $this->nestedMapper;
}
}