Completed
Push — master ( 589f5d...2e0cd6 )
by Pavel
07:02
created

RelationAwareProcessorDecorator::updateEntity()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 28
rs 8.439
cc 6
eloc 15
nc 2
nop 2
1
<?php
2
3
namespace ScayTrase\Api\Cruds\Adaptors\DoctrineOrm;
4
5
use Doctrine\Common\Persistence\ManagerRegistry;
6
use Doctrine\ORM\EntityManagerInterface;
7
use ScayTrase\Api\Cruds\EntityProcessorInterface;
8
9
final class RelationAwareProcessorDecorator implements EntityProcessorInterface
10
{
11
    /** @var  ManagerRegistry */
12
    private $registry;
13
    /** @var  EntityProcessorInterface */
14
    private $processor;
15
16
    /**
17
     * RelationAwareProcessorDecorator constructor.
18
     *
19
     * @param EntityProcessorInterface $processor
20
     * @param ManagerRegistry          $registry
21
     */
22
    public function __construct(EntityProcessorInterface $processor, ManagerRegistry $registry)
23
    {
24
        $this->registry  = $registry;
25
        $this->processor = $processor;
26
    }
27
28
    /** {@inheritdoc} */
29
    public function updateEntity($entity, $data)
30
    {
31
        $class = get_class($entity);
32
33
        $manager = $this->registry->getManagerForClass($class);
34
35
        if (null !== $manager) {
36
            $metadata = $manager->getClassMetadata($class);
37
38
            foreach ($data as $property => &$value) {
39
                if (null === $value) {
40
                    continue;
41
                }
42
43
                if ($metadata->hasAssociation($property)) {
44
                    $assoc = $metadata->getAssociationTargetClass($property);
45
46
                    if ($manager instanceof EntityManagerInterface) {
47
                        $value = $manager->getReference($assoc, $value);
48
                    } else {
49
                        $value = $manager->find($assoc, $value);
50
                    }
51
                }
52
            }
53
        }
54
55
        return $this->processor->updateEntity($entity, $data);
56
    }
57
}
58