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

RelationAwareProcessorDecorator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
c 2
b 0
f 0
lcom 1
cbo 5
dl 0
loc 49
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B updateEntity() 0 28 6
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