Completed
Pull Request — master (#14)
by Pavel
04:42
created

EntityHydrator::hydarate()   B

Complexity

Conditions 6
Paths 14

Size

Total Lines 45
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 6.3188

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 23
cts 29
cp 0.7931
rs 8.439
c 0
b 0
f 0
cc 6
eloc 27
nc 14
nop 2
crap 6.3188
1
<?php
2
3
namespace Bankiru\Api\Doctrine\Hydration;
4
5
use Bankiru\Api\Doctrine\EntityManager;
6
use Bankiru\Api\Doctrine\Exception\HydrationException;
7
use Bankiru\Api\Doctrine\Exception\MappingException;
8
use Bankiru\Api\Doctrine\Mapping\ApiMetadata;
9
use Bankiru\Api\Doctrine\Mapping\EntityMetadata;
10
use Doctrine\Common\Proxy\Proxy;
11
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
12
use Symfony\Component\PropertyAccess\PropertyAccessor;
13
14
class EntityHydrator
15
{
16
    /** @var  EntityMetadata */
17
    private $metadata;
18
    /** @var  EntityManager */
19
    private $manager;
20
21
    /**
22
     * EntityHydrator constructor.
23
     *
24
     * @param EntityManager $manager
25
     * @param ApiMetadata   $metadata
26
     */
27 13
    public function __construct(EntityManager $manager, ApiMetadata $metadata)
28
    {
29 13
        $this->manager  = $manager;
30 13
        $this->metadata = $metadata;
0 ignored issues
show
Documentation Bug introduced by
$metadata is of type object<Bankiru\Api\Doctrine\Mapping\ApiMetadata>, but the property $metadata was declared to be of type object<Bankiru\Api\Doctr...Mapping\EntityMetadata>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
31 13
    }
32
33
    /**
34
     * @param \StdClass   $source
35
     * @param object|null $entity
36
     *
37
     * @return object Hydrated object
38
     * @throws HydrationException
39
     */
40 13
    public function hydarate($source, $entity = null)
41
    {
42 13
        if (null === $entity) {
43 13
            $entity = $this->metadata->getReflectionClass()->newInstance();
44 13
        }
45
46 13
        $acessor = new PropertyAccessor();
47 13
        foreach ($this->metadata->getFieldNames() as $fieldName) {
48 13
            $property = $this->metadata->getReflectionProperty($fieldName);
49
50 13
            $apiField = $this->metadata->getApiFieldName($fieldName);
51
52
            try {
53 13
                $value = $acessor->getValue($source, $apiField);
54 13
            } catch (NoSuchPropertyException $exception) {
55 4
                if (!$this->metadata->getFieldMapping($fieldName)['nullable']) {
56
                    throw new HydrationException(
57
                        sprintf(
58
                            'Field %s for property %s does not present in dehydrated data',
59
                            $apiField,
60
                            $fieldName
61
                        )
62
                    );
63
                }
64
65 4
                $property->setValue($entity, null);
66
67 4
                continue;
68
            }
69
70
            $type  =
71 13
                $this->manager->getConfiguration()->getTypeRegistry()->get($this->metadata->getTypeOfField($fieldName));
72 13
            $value = $type->fromApiValue($value);
73
74 13
            $property->setValue($entity, $value);
75 13
        }
76
77 13
        foreach ($this->metadata->getAssociationNames() as $fieldName) {
78 10
            $value    = $this->hydrateAssociation($fieldName, $entity, $source);
79 10
            $property = $this->metadata->getReflectionProperty($fieldName);
80 10
            $property->setValue($entity, $value);
81 13
        }
82
83 13
        return $entity;
84
    }
85
86
    /**
87
     * @param string    $field
88
     * @param \StdClass $source
89
     * @param object    $entity
90
     *
91
     * @return array|Proxy|object
92
     * @throws HydrationException
93
     * @throws MappingException
94
     */
95 10
    private function hydrateAssociation($field, $entity, $source)
96
    {
97 10
        $accessor        = new PropertyAccessor();
98 10
        $targetClassName = $this->metadata->getAssociationTargetClass($field);
99 10
        $mapping         = $this->metadata->getAssociationMapping($field);
100 10
        $targetPersister = $this->manager->getUnitOfWork()->getEntityPersister($targetClassName);
101 10
        $targetMetadata  = $this->manager->getClassMetadata($mapping['target']);
102 10
        $apiField        = $mapping['api_field'];
103 10
        $field           = $mapping['field'];
104 10
        $oid             = spl_object_hash($entity);
105
106 10
        if ($this->metadata->isSingleValuedAssociation($field)) {
107 10
            $identifiers = $this->metadata->getIdentifierValues($entity);
108 10
            if ($mapping['isOwningSide']) {
109
                try {
110 10
                    $value = $accessor->getValue($source, $apiField);
111 10
                } catch (NoSuchPropertyException $exception) {
112 8
                    if ($mapping['nullable']) {
113 8
                        $this->manager->getUnitOfWork()->setOriginalEntityProperty($oid, $field, null);
114
115 8
                        return null;
116
                    }
117
118
                    throw new HydrationException(
119
                        sprintf('Api field %s for property %s does not present in response', $apiField, $field)
120
                    );
121
                }
122
123 5
                if ($targetMetadata->isIdentifierComposite()) {
124
                    throw new HydrationException('Composite references not supported');
125
                }
126
127 5
                $targetIdsNames = $targetMetadata->getIdentifierFieldNames();
128 5
                $targetIdName   = array_shift($targetIdsNames);
129 5
                $type           = $this->manager
130 5
                    ->getConfiguration()
131 5
                    ->getTypeRegistry()
132 5
                    ->get($targetMetadata->getTypeOfField($targetIdName));
133
134 5
                $identifiers = [$targetIdName => $type->fromApiValue($value)];
135 5
            }
136
137 5
            $newValue = $targetPersister->getToOneEntity($mapping, $entity, $identifiers);
138
139 5
            $this->manager->getUnitOfWork()->setOriginalEntityProperty($oid, $field, $newValue);
140
141 5
            return $newValue;
142 1
        }
143
144 10
        if ($this->metadata->isCollectionValuedAssociation($field)) {
145 10
            $newValue = $targetPersister->getOneToManyCollection($mapping, $entity);
146
147 10
            $this->manager->getUnitOfWork()->setOriginalEntityProperty($oid, $field, $newValue);
148
149 10
            return $newValue;
150
        }
151
152
        throw new MappingException('Invalid metadata association type');
153
    }
154
}
155