PasswordListener::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 2
cts 2
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace AppBundle\Security;
4
5
use Doctrine\ORM\Event\LifecycleEventArgs;
6
use Doctrine\ORM\Event\PreUpdateEventArgs;
7
use Doctrine\Common\EventSubscriber;
8
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
9
use Symfony\Component\Security\Core\User\UserInterface;
10
11
class PasswordListener implements EventSubscriber
12
{
13
    private $encoder;
14
15 15
    public function __construct(UserPasswordEncoder $encoder)
16
    {
17 15
        $this->encoder = $encoder;
18 15
    }
19 15
    public function getSubscribedEvents()
20
    {
21
        return array(
22 15
            'prePersist',
23
            'preUpdate',
24
        );
25
    }
26 3
    public function prePersist(LifecycleEventArgs $args)
27
    {
28 3
        $entity = $args->getEntity();
29
30 3
        if ($entity instanceof UserInterface && $entity->getPlainPassword()) {
31 1
            $this->encodePassword($entity);
32
        }
33 3
    }
34 8
    public function preUpdate(PreUpdateEventArgs $args)
35
    {
36 8
        $entity = $args->getEntity();
37
38 8
        if ($entity instanceof UserInterface && $entity->getPlainPassword()) {
39 2
            $this->encodePassword($entity);
40
        }
41 8
    }
42 3
    private function encodePassword($entity)
43
    {
44 3
        $password = $entity->getPlainPassword();
45 3
        $encoded = $this->encoder->encodePassword($entity, $password);
46 3
        $entity->setPassword($encoded);
47 3
    }
48
}
49