Completed
Push — master ( 98806f...27322f )
by Yann
02:14
created

DoctrineUserManager::getManagerFor()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Yokai\SecurityTokenBundle\Manager;
4
5
use Doctrine\Common\Persistence\ManagerRegistry;
6
use Doctrine\Common\Persistence\ObjectManager;
7
use Doctrine\Common\Util\ClassUtils;
8
9
/**
10
 * @author Yann Eugoné <[email protected]>
11
 */
12
class DoctrineUserManager implements UserManagerInterface
13
{
14
    /**
15
     * @var ManagerRegistry
16
     */
17
    private $doctrine;
18
19
    /**
20
     * @param ManagerRegistry $doctrine
21
     */
22 5
    public function __construct(ManagerRegistry $doctrine)
23
    {
24 5
        $this->doctrine = $doctrine;
25 5
    }
26
27
    /**
28
     * @inheritDoc
29
     */
30 2
    public function supportsClass($class)
31
    {
32
        try {
33 2
            $manager = $this->getManagerFor($class);
34 1
        } catch (\Exception $exception) {
35 1
            return false;
36
        }
37
38 1
        return $manager instanceof ObjectManager;
39
    }
40
41
    /**
42
     * @inheritDoc
43
     */
44 2
    public function supportsUser($user)
45
    {
46 2
        return $this->supportsClass(
47 2
            $this->getClass($user)
48
        );
49
    }
50
51
    /**
52
     * @inheritDoc
53
     */
54 1
    public function get($class, $id)
55
    {
56 1
        return $this->getManagerFor($class)->find($class, $id);
57
    }
58
59
    /**
60
     * @inheritDoc
61
     */
62 4
    public function getClass($user)
63
    {
64 4
        return ClassUtils::getClass($user);
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70 1
    public function getId($user)
71
    {
72 1
        $class = $this->getClass($user);
73 1
        $identifiers = $this->getManagerFor($class)->getClassMetadata($class)->getIdentifierValues($user);
74
75 1
        if (count($identifiers) > 1) {
76
            throw new \RuntimeException('Entities with composite ids are not supported');
77
        }
78
79 1
        return (string) reset($identifiers);
80
    }
81
82
    /**
83
     * @param string $class
84
     *
85
     * @return ObjectManager
86
     */
87 4
    private function getManagerFor($class)
88
    {
89 4
        $manager = $this->doctrine->getManagerForClass($class);
90
91 4
        if ($manager === null) {
92 1
            throw new \RuntimeException(
93 1
                sprintf(
94 1
                    'Class "%s" seems not to be a managed Doctrine entity. Did you forget to map it?',
95 1
                    $class
96
                )
97
            );
98
        }
99
100 3
        return $manager;
101
    }
102
}
103