Passed
Pull Request — master (#1636)
by Tarmo
09:53
created

SecurityUserFactory::loadUserByUsername()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Security/Provider/SecurityUserFactory.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Security\Provider;
10
11
use App\Entity\User;
12
use App\Repository\UserRepository;
13
use App\Security\RolesService;
14
use App\Security\SecurityUser;
15
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
16
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
17
use Symfony\Component\Security\Core\User\UserInterface;
18
use Symfony\Component\Security\Core\User\UserProviderInterface;
19
use Throwable;
20
21
/**
22
 * Class SecurityUserFactory
23
 *
24
 * @package App\Security\Provider
25
 * @author TLe, Tarmo Leppänen <[email protected]>
26
 */
27
class SecurityUserFactory implements UserProviderInterface
28
{
29 289
    public function __construct(
30
        private UserRepository $userRepository,
31
        private RolesService $rolesService,
32
        private string $uuidV1Regex,
33
    ) {
34 289
    }
35
36 8
    public function supportsClass(string $class): bool
37
    {
38 8
        return $class === SecurityUser::class;
39
    }
40
41
    /**
42
     * {@inheritDoc}
43
     *
44
     * @throws Throwable
45
     */
46 274
    public function loadUserByIdentifier(string $identifier): SecurityUser
47
    {
48 274
        $user = $this->userRepository->loadUserByIdentifier(
49 274
            $identifier,
50 274
            (bool)preg_match('#' . $this->uuidV1Regex . '#', $identifier)
51
        );
52
53 274
        if (!($user instanceof User)) {
54 8
            throw new UserNotFoundException(sprintf('User not found for UUID: "%s".', $identifier));
55
        }
56
57 266
        return new SecurityUser($user, $this->rolesService->getInheritedRoles($user->getRoles()));
58
    }
59
60
    /**
61
     * @throws Throwable
62
     */
63 7
    public function refreshUser(UserInterface $user): SecurityUser
64
    {
65 7
        if (!($user instanceof SecurityUser)) {
66 2
            throw new UnsupportedUserException(sprintf('Invalid user class "%s".', $user::class));
67
        }
68
69 5
        $userEntity = $this->userRepository->find($user->getUserIdentifier());
70
71 5
        if (!($userEntity instanceof User)) {
72 2
            throw new UserNotFoundException(sprintf('User not found for UUID: "%s".', $user->getUserIdentifier()));
73
        }
74
75 3
        return new SecurityUser($userEntity, $this->rolesService->getInheritedRoles($userEntity->getRoles()));
76
    }
77
}
78