Completed
Push — master ( f26b67...aac01d )
by Jeff
02:53
created

UserProvider::loadUserByUsername()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the mailserver-admin package.
6
 * (c) Jeffrey Boehm <https://github.com/jeboehm/mailserver-admin>
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace App\Security\Provider;
12
13
use App\Entity\User;
14
use App\Repository\UserRepository;
15
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
16
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
17
use Symfony\Component\Security\Core\User\UserInterface;
18
use Symfony\Component\Security\Core\User\UserProviderInterface;
19
20
class UserProvider implements UserProviderInterface
21
{
22
    private $userRepository;
23
24
    public function __construct(UserRepository $userRepository)
25
    {
26
        $this->userRepository = $userRepository;
27
    }
28
29
    public function refreshUser(UserInterface $user): User
30
    {
31
        if (!($user instanceof User)) {
32
            throw new UnsupportedUserException(
33
                sprintf('Instances of "%s" are not supported.', \get_class($user))
34
            );
35
        }
36
37
        return $this->loadUserByUsername((string) $user);
38
    }
39
40
    public function loadUserByUsername($username): User
41
    {
42
        $user = $this->userRepository->findOneByEmailAddress((string) $username);
43
44
        if (!$user || '' === $user->getPassword()) {
45
            throw new UsernameNotFoundException(sprintf('Address "%s" not found or not permitted.', $username));
46
        }
47
48
        if ($user->isAdmin()) {
49
            $user->addRole('ROLE_ADMIN');
50
        }
51
52
        return $user;
53
    }
54
55
    public function supportsClass($class): bool
56
    {
57
        return User::class === $class;
58
    }
59
}
60