PasswordHashListener   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 6
dl 0
loc 60
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSubscribedEvents() 0 7 1
A prePersist() 0 13 3
A preUpdate() 0 15 3
A updatePasswordHash() 0 12 2
1
<?php
2
3
namespace Knp\RadBundle\Doctrine\Listener;
4
5
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
6
7
use Doctrine\Common\EventSubscriber;
8
use Doctrine\ORM\Events;
9
use Doctrine\ORM\Event\LifecycleEventArgs;
10
use Doctrine\ORM\Event\PreUpdateEventArgs;
11
12
use Knp\RadBundle\Security\UserInterface;
13
use Knp\RadBundle\Security\RecoverableUserInterface;
14
15
class PasswordHashListener implements EventSubscriber
16
{
17
    private $encoderFactory;
18
19
    public function __construct(EncoderFactoryInterface $encoderFactory)
20
    {
21
        $this->encoderFactory = $encoderFactory;
22
    }
23
24
    public function getSubscribedEvents()
25
    {
26
        return array(
27
            Events::prePersist,
28
            Events::preUpdate,
29
        );
30
    }
31
32
    public function prePersist(LifecycleEventArgs $args)
33
    {
34
        $entity = $args->getEntity();
35
36
        if (!$entity instanceof UserInterface) {
37
            return;
38
        }
39
        if (null === $entity->getPlainPassword()) {
40
            return;
41
        }
42
43
        $this->updatePasswordHash($entity);
44
    }
45
46
    public function preUpdate(PreUpdateEventArgs $args)
47
    {
48
        $entity = $args->getEntity();
49
50
        if (!$entity instanceof UserInterface) {
51
            return;
52
        }
53
        if (null === $entity->getPlainPassword()) {
54
            return;
55
        }
56
57
        $this->updatePasswordHash($entity);
58
59
        $args->setNewValue('password', $entity->getPassword());
60
    }
61
62
    private function updatePasswordHash(UserInterface $entity)
63
    {
64
        $password = $this->encoderFactory->getEncoder($entity)->encodePassword(
65
            $entity->getPlainPassword(), $entity->getSalt()
66
        );
67
        $entity->setPassword($password);
68
        $entity->eraseCredentials();
69
70
        if ($entity instanceof RecoverableUserInterface) {
71
            $entity->erasePasswordRecoveryKey();
72
        }
73
    }
74
}
75