EntityUserProvider   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 122
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 48
dl 0
loc 122
ccs 0
cts 50
cp 0
rs 10
c 0
b 0
f 0
wmc 21

8 Methods

Rating   Name   Duplication   Size   Complexity  
A supportsClass() 0 3 2
A getRepository() 0 3 1
A __construct() 0 5 1
A upgradePassword() 0 12 3
A loadUserByIdentifier() 0 18 5
A getClass() 0 13 3
A getClassMetadata() 0 3 1
A refreshUser() 0 32 5
1
<?php declare(strict_types=1);
2
3
/*
4
 * This file is part of Biurad opensource projects.
5
 *
6
 * @copyright 2019 Biurad Group (https://biurad.com/)
7
 * @license   https://opensource.org/licenses/BSD-3-Clause License
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Flange\Database\Doctrine\Provider;
14
15
use Doctrine\Persistence\Mapping\ClassMetadata;
16
use Doctrine\Persistence\ObjectManager;
17
use Doctrine\Persistence\ObjectRepository;
18
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
19
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
20
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
21
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
22
use Symfony\Component\Security\Core\User\UserInterface;
23
use Symfony\Component\Security\Core\User\UserProviderInterface;
24
25
/**
26
 * Wrapper around a Doctrine ObjectManager.
27
 *
28
 * Provides provisioning for Doctrine entity users.
29
 *
30
 * @author Fabien Potencier <[email protected]>
31
 * @author Johannes M. Schmitt <[email protected]>
32
 */
33
class EntityUserProvider implements UserProviderInterface, PasswordUpgraderInterface
34
{
35
    private ObjectManager $objectManager;
36
    private string $classOrAlias;
37
    private ?string $property;
38
    private ?string $class = null;
39
40
    public function __construct(ObjectManager $objectManager, string $classOrAlias, string $property = 'username')
41
    {
42
        $this->objectManager = $objectManager;
43
        $this->classOrAlias = $classOrAlias;
44
        $this->property = $property;
45
    }
46
47
    public function loadUserByIdentifier(string $identifier): UserInterface
48
    {
49
        $repository = $this->getRepository();
50
51
        if ($repository instanceof UserLoaderInterface || $repository instanceof UserProviderInterface) {
52
            $user = $repository->loadUserByIdentifier($identifier);
53
        } elseif (null === $this->property) {
54
            throw new \InvalidArgumentException(\sprintf('You must either make the "%s" entity Doctrine Repository ("%s") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.', $this->classOrAlias, \get_debug_type($repository)));
55
        }
56
57
        if (null === $user = ($user ?? $repository->findOneBy([$this->property => $identifier]))) {
58
            $e = new UserNotFoundException(\sprintf('User "%s" not found.', $identifier));
59
            $e->setUserIdentifier($identifier);
60
61
            throw $e;
62
        }
63
64
        return $user;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function refreshUser(UserInterface $user): UserInterface
71
    {
72
        $class = $this->getClass();
73
74
        if (!$user instanceof $class) {
75
            throw new UnsupportedUserException(\sprintf('Instances of "%s" are not supported.', \get_debug_type($user)));
76
        }
77
78
        $repository = $this->getRepository();
79
80
        if ($repository instanceof UserProviderInterface) {
81
            $refreshedUser = $repository->refreshUser($user);
82
        } else {
83
            // The user must be reloaded via the primary key as all other data
84
            // might have changed without proper persistence in the database.
85
            // That's the case when the user has been changed by a form with
86
            // validation errors.
87
            if (!$id = $this->getClassMetadata()->getIdentifierValues($user)) {
88
                throw new \InvalidArgumentException('You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.');
89
            }
90
91
            $refreshedUser = $repository->find($id);
92
93
            if (null === $refreshedUser) {
94
                $e = new UserNotFoundException('User with id '.\json_encode($id).' not found.');
95
                $e->setUserIdentifier(\json_encode($id));
96
97
                throw $e;
98
            }
99
        }
100
101
        return $refreshedUser;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function supportsClass(string $class): bool
108
    {
109
        return $class === $this->getClass() || \is_subclass_of($class, $this->getClass());
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     *
115
     * @final
116
     */
117
    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
118
    {
119
        $class = $this->getClass();
120
121
        if (!$user instanceof $class) {
122
            throw new UnsupportedUserException(\sprintf('Instances of "%s" are not supported.', \get_debug_type($user)));
123
        }
124
125
        $repository = $this->getRepository();
126
127
        if ($repository instanceof PasswordUpgraderInterface) {
128
            $repository->upgradePassword($user, $newHashedPassword);
129
        }
130
    }
131
132
    private function getRepository(): ObjectRepository
133
    {
134
        return $this->objectManager->getRepository($this->classOrAlias);
135
    }
136
137
    private function getClass(): string
138
    {
139
        if (!isset($this->class)) {
140
            $class = $this->classOrAlias;
141
142
            if (\str_contains($class, ':')) {
143
                $class = $this->getClassMetadata()->getName();
144
            }
145
146
            $this->class = $class;
147
        }
148
149
        return $this->class;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->class could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
150
    }
151
152
    private function getClassMetadata(): ClassMetadata
153
    {
154
        return $this->objectManager->getClassMetadata($this->classOrAlias);
155
    }
156
}
157