1
|
|
|
<?php |
2
|
|
|
namespace pmill\Doctrine\Hydrator; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Json API Request Doctrine Hydrator |
6
|
|
|
* @link http://jsonapi.org/format/#document-resource-objects |
7
|
|
|
*/ |
8
|
|
|
class JsonApiHydrator extends ArrayHydrator |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @param $entity |
12
|
|
|
* @param $data |
13
|
|
|
* |
14
|
|
|
* @return object |
15
|
|
|
*/ |
16
|
|
|
protected function hydrateProperties($entity, $data) |
17
|
|
|
{ |
18
|
|
|
if (isset($data['attributes']) && is_array($data['attributes'])) { |
19
|
|
|
$entity = parent::hydrateProperties($entity, $data['attributes']); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
return $entity; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Map JSON API resource relations to doctrine entity. |
27
|
|
|
* |
28
|
|
|
* @param object $entity |
29
|
|
|
* @param array $data |
30
|
|
|
* |
31
|
|
|
* @return mixed |
32
|
|
|
* @throws \Exception |
33
|
|
|
*/ |
34
|
|
|
protected function hydrateAssociations($entity, $data) |
35
|
|
|
{ |
36
|
|
|
if (isset($data['relationships']) && is_array($data['relationships'])) { |
37
|
|
|
$metadata = $this->entityManager->getClassMetadata(get_class($entity)); |
38
|
|
|
|
39
|
|
|
foreach ($data['relationships'] as $name => $data) { |
40
|
|
|
if (!isset($metadata->associationMappings[$name])) { |
41
|
|
|
throw new \Exception(sprintf('Relation `%s` association not found', $name)); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if (is_array($data['data'])) { |
45
|
|
|
if (isset($data['data']['id']) && isset($data['data']['type'])) { |
46
|
|
|
$this->hydrateToOneAssociation($entity, $name, |
47
|
|
|
$metadata->associationMappings[$name], |
48
|
|
|
$data['data']['id'] |
49
|
|
|
); |
50
|
|
|
} else { |
51
|
|
|
$this->hydrateToManyAssociation($entity, $name, |
52
|
|
|
$metadata->associationMappings[$name], |
53
|
|
|
array_map( |
54
|
|
|
function ($relation) { |
55
|
|
|
if (isset($relation['id']) && isset($relation['type'])) { |
56
|
|
|
return $relation['id']; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return ['attributes' => $relation]; |
60
|
|
|
}, |
61
|
|
|
$data['data'] |
62
|
|
|
) |
63
|
|
|
); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $entity; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|