RelationAwareProcessorDecorator::updateEntity()   B
last analyzed

Complexity

Conditions 6
Paths 2

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 14
cts 14
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 15
nc 2
nop 2
crap 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 6
    public function __construct(EntityProcessorInterface $processor, ManagerRegistry $registry)
23
    {
24 6
        $this->registry  = $registry;
25 6
        $this->processor = $processor;
26 6
    }
27
28
    /** {@inheritdoc} */
29 6
    public function updateEntity($entity, $data)
30
    {
31 6
        $class = get_class($entity);
32
33 6
        $manager = $this->registry->getManagerForClass($class);
34
35 6
        if (null !== $manager) {
36 6
            $metadata = $manager->getClassMetadata($class);
37
38 6
            foreach ($data as $property => &$value) {
39 6
                if (null === $value) {
40 1
                    continue;
41
                }
42
43 6
                if ($metadata->hasAssociation($property)) {
44 3
                    $assoc = $metadata->getAssociationTargetClass($property);
45
46 3
                    if ($manager instanceof EntityManagerInterface) {
47 3
                        $value = $manager->getReference($assoc, $value);
48
                    } else {
49 6
                        $value = $manager->find($assoc, $value);
50
                    }
51
                }
52
            }
53
        }
54
55 6
        return $this->processor->updateEntity($entity, $data);
56
    }
57
}
58