Test Failed
Push — master ( c9ae9e...7a82a2 )
by Pavel
01:40
created

JsonApiHydrator::mapRelationshipsArray()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 1
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace App;
3
use pmill\Doctrine\Hydrator\ArrayHydrator;
4
5
/**
6
 * Json API Request Doctrine Hydrator
7
 * @link http://jsonapi.org/format/#document-resource-objects
8
 */
9
class JsonApiHydrator extends ArrayHydrator
10
{
11
    /**
12
     * @param $entity
13
     * @param $data
14
     *
15
     * @return object
16
     */
17
    protected function hydrateProperties($entity, $data)
18
    {
19
        if (isset($data['attributes']) && is_array($data['attributes'])) {
20
            $entity = parent::hydrateProperties($entity, $data['attributes']);
21
        }
22
23
        return $entity;
24
    }
25
26
    /**
27
     * Map JSON API resource relations to doctrine entity.
28
     *
29
     * @param object $entity
30
     * @param array  $data
31
     *
32
     * @return mixed
33
     * @throws \Exception
34
     */
35
    protected function hydrateAssociations($entity, $data)
36
    {
37
        if (isset($data['relationships']) && is_array($data['relationships'])) {
38
            $metadata = $this->entityManager->getClassMetadata(get_class($entity));
39
40
            foreach ($data['relationships'] as $name => $data) {
41
                if (!isset($metadata->associationMappings[$name])) {
42
                    throw new \Exception(sprintf('Relation `%s` association not found', $name));
43
                }
44
45
                $mapping = $metadata->associationMappings[$name];
46
47
                if (is_array($data['data'])) {
48
                    if ($resourceId = $this->getResourceId($data['data'])) {
49
                        $this->hydrateToOneAssociation($entity, $name, $mapping, $resourceId);
50
                    } else {
51
                        $this->hydrateToManyAssociation($entity, $name, $mapping,
52
                            $this->mapRelationshipsArray($data['data'])
53
                        );
54
                    }
55
                }
56
            }
57
        }
58
59
        return $entity;
60
    }
61
62
    /**
63
     * @param array $data
64
     *
65
     * @return array
66
     */
67
    protected function mapRelationshipsArray(array $data)
68
    {
69
        return array_map(
70
            function ($relation) {
71
                return $this->getResourceId($relation) ?: ['attributes' => $relation];
72
            },
73
            $data
74
        );
75
    }
76
77
    /**
78
     * @param array $data
79
     *
80
     * @return int|null
81
     */
82
    protected function getResourceId(array $data)
83
    {
84
        if (isset($data['id']) && isset($data['type'])) {
85
            return $data['id'];
86
        }
87
88
        return null;
89
    }
90
}
91