Completed
Push — master ( c00bbf...06e52a )
by Pavel
17:08 queued 22s
created

EntityToIdNormalizer::normalize()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 2
nop 1
crap 3.0261
1
<?php
2
3
namespace ScayTrase\Api\Cruds\Adaptors\DoctrineOrm;
4
5
use Doctrine\Common\Persistence\ManagerRegistry;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Doctrine\ORM\Mapping\ClassMetadata;
8
9
final class EntityToIdNormalizer
10
{
11
    /** @var  ManagerRegistry */
12
    private $registry;
13
14
    /**
15
     * EntityToIdConverter constructor.
16
     *
17
     * @param ManagerRegistry $registry
18
     */
19 21
    public function __construct(ManagerRegistry $registry)
20
    {
21 21
        $this->registry = $registry;
22 21
    }
23
24
    /**
25
     * @param $entity
26
     *
27
     * @return mixed|array
28
     */
29 7
    public function normalize($entity)
30
    {
31 7
        $class    = get_class($entity);
32 7
        $metadata = $this->registry->getManagerForClass($class)->getClassMetadata($class);
33
34 7
        $ids = $metadata->getIdentifierValues($entity);
35
36 7
        if (!$metadata instanceof ClassMetadata || $metadata->isIdentifierComposite) {
37
            return $ids;
38
        }
39
40 7
        return array_shift($ids);
41
    }
42
43
    /**
44
     * @param mixed|array $identifier
45
     * @param string      $class
46
     *
47
     * @return object
48
     *
49
     * @throws \Doctrine\ORM\ORMException
50
     */
51 1
    public function denormalize($identifier, $class)
52
    {
53 1
        $manager = $this->registry->getManagerForClass($class);
54
55 1
        if (null === $manager) {
56
            throw new \RuntimeException('Not supported class '.$class);
57
        }
58
59 1
        if ($manager instanceof EntityManagerInterface) {
60 1
            return $manager->getReference($class, $identifier);
61
        }
62
63
        return $manager->find($class, $identifier);
64
    }
65
}
66