Completed
Push — master ( e61615...870684 )
by Pavel
04:58
created

EntityToIdNormalizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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
    public function __construct(ManagerRegistry $registry)
20
    {
21
        $this->registry = $registry;
22
    }
23
24
    /**
25
     * @param $entity
26
     *
27
     * @return mixed|array
28
     */
29
    public function normalize($entity)
30
    {
31
        $class    = get_class($entity);
32
        $metadata = $this->registry->getManagerForClass($class)->getClassMetadata($class);
33
34
        $ids = $metadata->getIdentifierValues($entity);
35
36
        if (!$metadata instanceof ClassMetadata || $metadata->isIdentifierComposite) {
37
            return $ids;
38
        }
39
40
        return array_shift($ids);
41
    }
42
43
    /**
44
     * @param mixed|array $identifier
45
     * @param string      $class
46
     *
47
     * @return object
48
     */
49
    public function denormalize($identifier, $class)
50
    {
51
        $manager = $this->registry->getManagerForClass($class);
52
53
        if (null === $manager) {
54
            throw new \RuntimeException('Not supported class '.$class);
55
        }
56
57
        if ($manager instanceof EntityManagerInterface) {
58
            return $manager->getReference($class, $identifier);
59
        }
60
61
        return $manager->find($class, $identifier);
62
    }
63
}
64