Completed
Pull Request — master (#14)
by Pavel
03:32
created

EntityHydrator::hydrateAssociation()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 59
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 7.1032

Importance

Changes 0
Metric Value
dl 0
loc 59
ccs 34
cts 39
cp 0.8718
rs 7.5346
c 0
b 0
f 0
cc 7
eloc 37
nc 7
nop 3
crap 7.1032

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 12
    public function __construct(EntityManager $manager, ApiMetadata $metadata)
28
    {
29 12
        $this->manager  = $manager;
30 12
        $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 12
    }
32
33
    /**
34
     * @param \StdClass   $source
35
     * @param object|null $entity
36
     *
37
     * @return object Hydrated object
38
     * @throws HydrationException
39
     */
40 12
    public function hydarate($source, $entity = null)
41
    {
42 12
        if (null === $entity) {
43 12
            $entity = $this->metadata->getReflectionClass()->newInstance();
44 12
        }
45
46 12
        $acessor = new PropertyAccessor();
47 12
        foreach ($this->metadata->getFieldNames() as $fieldName) {
48 12
            $property = $this->metadata->getReflectionProperty($fieldName);
49
50 12
            $apiField = $this->metadata->getApiFieldName($fieldName);
51
52
            try {
53 12
                $value = $acessor->getValue($source, $apiField);
54 12
            } 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 12
                $this->manager->getConfiguration()->getTypeRegistry()->get($this->metadata->getTypeOfField($fieldName));
72 12
            $value = $type->fromApiValue($value);
73
74 12
            $property->setValue($entity, $value);
75 12
        }
76
77 12
        foreach ($this->metadata->getAssociationNames() as $fieldName) {
78 9
            $value    = $this->hydrateAssociation($fieldName, $entity, $source);
79 9
            $property = $this->metadata->getReflectionProperty($fieldName);
80 9
            $property->setValue($entity, $value);
81 12
        }
82
83 12
        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 9
    private function hydrateAssociation($field, $entity, $source)
96
    {
97 9
        $accessor        = new PropertyAccessor();
98 9
        $targetClassName = $this->metadata->getAssociationTargetClass($field);
99 9
        $mapping         = $this->metadata->getAssociationMapping($field);
100 9
        $targetPersister = $this->manager->getUnitOfWork()->getEntityPersister($targetClassName);
101 9
        $targetMetadata  = $this->manager->getClassMetadata($mapping['target']);
102 9
        $apiField        = $mapping['api_field'];
103 9
        $field           = $mapping['field'];
104 9
        $oid             = spl_object_hash($entity);
105
106 9
        if ($this->metadata->isSingleValuedAssociation($field)) {
107 9
            $identifiers = $this->metadata->getIdentifierValues($entity);
108 9
            if ($mapping['isOwningSide']) {
109
                try {
110 9
                    $value = $accessor->getValue($source, $apiField);
111 9
                } 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 4
                if ($targetMetadata->isIdentifierComposite()) {
124
                    throw new HydrationException('Composite references not supported');
125
                }
126
127 4
                $targetIdsNames = $targetMetadata->getIdentifierFieldNames();
128 4
                $targetIdName   = array_shift($targetIdsNames);
129 4
                $type           = $this->manager
130 4
                    ->getConfiguration()
131 4
                    ->getTypeRegistry()
132 4
                    ->get($targetMetadata->getTypeOfField($targetIdName));
133
134 4
                $identifiers = [$targetIdName => $type->fromApiValue($value)];
135 4
            }
136
137 4
            $newValue = $targetPersister->getToOneEntity($mapping, $entity, $identifiers);
138
139 4
            $this->manager->getUnitOfWork()->setOriginalEntityProperty($oid, $field, $newValue);
140
141 4
            return $newValue;
142 1
        }
143
144 9
        if ($this->metadata->isCollectionValuedAssociation($field)) {
145 9
            $newValue = $targetPersister->getOneToManyCollection($mapping, $entity);
146
147 9
            $this->manager->getUnitOfWork()->setOriginalEntityProperty($oid, $field, $newValue);
148
149 9
            return $newValue;
150
        }
151
152
        throw new MappingException('Invalid metadata association type');
153
    }
154
}
155