Passed
Push — master ( ccb0ad...db579c )
by Gerard
03:01 queued 42s
created

UserRepository::encodePassword()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gbere\SimpleAuth\Repository;
6
7
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
8
use Doctrine\Common\Persistence\ManagerRegistry;
9
use Doctrine\ORM\OptimisticLockException;
10
use Doctrine\ORM\ORMException;
11
use Gbere\SimpleAuth\Entity\UserInterface;
12
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
13
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
14
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
15
16
/**
17
 * @method UserInterface|null find($id, $lockMode = null, $lockVersion = null)
18
 * @method UserInterface|null findOneBy(array $criteria, array $orderBy = null)
19
 * @method UserInterface[]    findAll()
20
 * @method UserInterface[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
21
 */
22
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
23
{
24
    /** @var UserPasswordEncoderInterface */
25
    protected $passwordEncoder;
26
27
    public function __construct(ManagerRegistry $registry, UserInterface $user, UserPasswordEncoderInterface $passwordEncoder)
28
    {
29
        $this->passwordEncoder = $passwordEncoder;
30
31
        parent::__construct($registry, \get_class($user));
32
    }
33
34
    /**
35
     * @throws ORMException
36
     * @throws OptimisticLockException
37
     */
38
    public function upgradePassword($user, string $newEncodedPassword): void
39
    {
40
        if (!$user instanceof UserInterface) {
41
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
42
        }
43
44
        $user->setPassword($newEncodedPassword);
45
        $this->_em->persist($user);
46
        $this->_em->flush();
47
    }
48
49
    public function createUser(): UserInterface
50
    {
51
        return new $this->_entityName();
52
    }
53
54
    public function encodePassword(string $password): string
55
    {
56
        return $this->passwordEncoder->encodePassword(new $this->_entityName(), $password);
57
    }
58
59
    /**
60
     * @throws ORMException
61
     * @throws OptimisticLockException
62
     */
63
    public function persistAndFlush(UserInterface $user): void
64
    {
65
        $this->_em->persist($user);
66
        $this->_em->flush();
67
    }
68
}
69