-
Notifications
You must be signed in to change notification settings - Fork 38
/
HydratorTrait.php
269 lines (234 loc) · 9.19 KB
/
HydratorTrait.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<?php
declare(strict_types=1);
namespace WoohooLabs\Yin\JsonApi\Hydrator;
use Closure;
use ReflectionFunction;
use WoohooLabs\Yin\JsonApi\Exception\ExceptionFactoryInterface;
use WoohooLabs\Yin\JsonApi\Exception\JsonApiExceptionInterface;
use WoohooLabs\Yin\JsonApi\Exception\RelationshipTypeInappropriate;
use WoohooLabs\Yin\JsonApi\Hydrator\Relationship\ToManyRelationship;
use WoohooLabs\Yin\JsonApi\Hydrator\Relationship\ToOneRelationship;
use WoohooLabs\Yin\JsonApi\Schema\ResourceIdentifier;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function count;
use function in_array;
trait HydratorTrait
{
/**
* Determines which resource types can be accepted by the hydrator.
*
* The method should return an array of acceptable resource types. When such a resource is received for hydration
* which can't be accepted (its type doesn't match the acceptable types of the hydrator), a ResourceTypeUnacceptable
* exception will be raised.
* @return list<string>
*/
abstract protected function getAcceptedTypes(): array;
/**
* Provides the attribute hydrators.
*
* The method returns an array of attribute hydrators, where a hydrator is a key-value pair:
* the key is the specific attribute name which comes from the request and the value is a
* callable which hydrates the given attribute.
* These callables receive the domain object (which will be hydrated), the value of the
* currently processed attribute, the "data" part of the request and the name of the attribute
* to be hydrated as their arguments, and they should mutate the state of the domain object.
* If it is an immutable object or an array (and passing by reference isn't used),
* the callable should return the domain object.
* @param mixed $domainObject
* @return array<string, callable>
*/
abstract protected function getAttributeHydrator($domainObject): array;
/**
* Provides the relationship hydrators.
*
* The method returns an array of relationship hydrators, where a hydrator is a key-value pair:
* the key is the specific relationship name which comes from the request and the value is an
* callable which hydrate the previous relationship.
* These callables receive the domain object (which will be hydrated), an object representing the
* currently processed relationship (it can be a ToOneRelationship or a ToManyRelationship
* object), the "data" part of the request and the relationship name as their arguments, and
* they should mutate the state of the domain object.
* If it is an immutable object or an array (and passing by reference isn't used),
* the callable should return the domain object.
* @param mixed $domainObject
* @return array<string, callable>
*/
abstract protected function getRelationshipHydrator($domainObject): array;
/**
* @throws JsonApiExceptionInterface
*/
protected function validateType(array $data, ExceptionFactoryInterface $exceptionFactory): void
{
if (empty($data["type"])) {
throw $exceptionFactory->createResourceTypeMissingException();
}
$acceptedTypes = $this->getAcceptedTypes();
if (in_array($data["type"], $acceptedTypes, true) === false) {
throw $exceptionFactory->createResourceTypeUnacceptableException($data["type"], $acceptedTypes);
}
}
/**
* @param mixed $domainObject
* @return mixed
*/
protected function hydrateAttributes($domainObject, array $data)
{
if (empty($data["attributes"])) {
return $domainObject;
}
$attributeHydrator = $this->getAttributeHydrator($domainObject);
foreach ($attributeHydrator as $attribute => $hydrator) {
if (array_key_exists($attribute, $data["attributes"]) === false) {
continue;
}
$result = $hydrator($domainObject, $data["attributes"][$attribute], $data, $attribute);
if ($result) {
$domainObject = $result;
}
}
return $domainObject;
}
/**
* @param mixed $domainObject
* @return mixed
*/
protected function hydrateRelationships($domainObject, array $data, ExceptionFactoryInterface $exceptionFactory)
{
if (empty($data["relationships"])) {
return $domainObject;
}
$relationshipHydrator = $this->getRelationshipHydrator($domainObject);
foreach ($relationshipHydrator as $relationship => $hydrator) {
if (isset($data["relationships"][$relationship]) === false) {
continue;
}
$domainObject = $this->doHydrateRelationship(
$domainObject,
$relationship,
$hydrator,
$exceptionFactory,
$data["relationships"][$relationship],
$data
);
}
return $domainObject;
}
/**
* @param mixed $domainObject
* @return mixed
*/
protected function doHydrateRelationship(
$domainObject,
string $relationshipName,
callable $hydrator,
ExceptionFactoryInterface $exceptionFactory,
?array $relationshipData,
?array $data
) {
$relationshipObject = $this->createRelationship(
$relationshipData,
$exceptionFactory
);
if ($relationshipObject !== null) {
$result = $this->getRelationshipHydratorResult(
$relationshipName,
$hydrator,
$domainObject,
$relationshipObject,
$data,
$exceptionFactory
);
if ($result !== null) {
$domainObject = $result;
}
}
return $domainObject;
}
/**
* @param mixed $domainObject
* @param ToOneRelationship|ToManyRelationship $relationshipObject
* @return mixed
* @throws RelationshipTypeInappropriate|JsonApiExceptionInterface
*/
protected function getRelationshipHydratorResult(
string $relationshipName,
callable $hydrator,
$domainObject,
$relationshipObject,
?array $data,
ExceptionFactoryInterface $exceptionFactory
) {
// Checking if the current and expected relationship types match
$relationshipType = $this->getRelationshipType($relationshipObject);
$expectedRelationshipType = $this->getRelationshipType($this->getArgumentTypeHintFromCallable($hydrator));
if ($expectedRelationshipType !== "" && $relationshipType !== $expectedRelationshipType) {
throw $exceptionFactory->createRelationshipTypeInappropriateException(
$relationshipName,
$relationshipType,
$expectedRelationshipType
);
}
// Returning if the hydrator returns the hydrated domain object
$value = $hydrator($domainObject, $relationshipObject, $data, $relationshipName);
if ($value) {
return $value;
}
// Returning the domain object which was mutated but not returned by the hydrator
return $domainObject;
}
protected function getArgumentTypeHintFromCallable(callable $callable): ?string
{
$function = &$callable;
$reflection = new ReflectionFunction(Closure::fromCallable($function));
$arguments = $reflection->getParameters();
$class = isset($arguments[1]) ? $arguments[1]->getClass() : null;
if ($class === null) {
return null;
}
return $class->getName();
}
/**
* @param object|string|null $object
*/
protected function getRelationshipType($object): string
{
if ($object instanceof ToOneRelationship || $object === ToOneRelationship::class) {
return "to-one";
}
if ($object instanceof ToManyRelationship || $object === ToManyRelationship::class) {
return "to-many";
}
return "";
}
/**
* @return ToOneRelationship|ToManyRelationship|null
*/
private function createRelationship(?array $relationship, ExceptionFactoryInterface $exceptionFactory)
{
if ($relationship === null || array_key_exists("data", $relationship) === false) {
return null;
}
//If this is a request to clear the relationship, we create an empty relationship
if ($relationship["data"] === null) {
$result = new ToOneRelationship();
} elseif ($this->isAssociativeArray($relationship["data"])) {
$result = new ToOneRelationship(
ResourceIdentifier::fromArray($relationship["data"], $exceptionFactory)
);
} else {
$result = new ToManyRelationship();
foreach ($relationship["data"] as $data) {
$result->addResourceIdentifier(
ResourceIdentifier::fromArray($data, $exceptionFactory)
);
}
}
return $result;
}
private function isAssociativeArray(array $array): bool
{
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
}