EncodePasswordListener::onUserCreated()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * (c) FSi sp. z o.o. <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace FSi\Bundle\AdminSecurityBundle\EventListener;
13
14
use FSi\Bundle\AdminSecurityBundle\Event\AdminSecurityEvents;
15
use FSi\Bundle\AdminSecurityBundle\Event\ChangePasswordEvent;
16
use FSi\Bundle\AdminSecurityBundle\Event\UserEvent;
17
use FSi\Bundle\AdminSecurityBundle\Security\User\UserInterface;
18
use FSi\Bundle\AdminSecurityBundle\Security\User\ChangeablePasswordInterface;
19
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
20
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
21
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
22
23
class EncodePasswordListener implements EventSubscriberInterface
24
{
25
    /**
26
     * @var EncoderFactoryInterface
27
     */
28
    private $encoderFactory;
29
30
    public function __construct(EncoderFactoryInterface $encoderFactory)
31
    {
32
        $this->encoderFactory = $encoderFactory;
33
    }
34
35
    public static function getSubscribedEvents(): array
36
    {
37
        return [
38
            AdminSecurityEvents::CHANGE_PASSWORD => 'onChangePassword',
39
            AdminSecurityEvents::USER_CREATED => 'onUserCreated'
40
        ];
41
    }
42
43
    public function onChangePassword(ChangePasswordEvent $event): void
44
    {
45
        $this->updateUserPassword($event->getUser());
46
    }
47
48
    /**
49
     * @param UserEvent $event
50
     */
51
    public function onUserCreated(UserEvent $event)
52
    {
53
        $user = $event->getUser();
54
        if ($user instanceof ChangeablePasswordInterface) {
55
            $this->updateUserPassword($user);
56
        }
57
    }
58
59
    protected function updateUserPassword(ChangeablePasswordInterface $user): void
60
    {
61
        $password = $user->getPlainPassword();
62
        if (null !== $password) {
63
            $encoder = $this->getEncoder($user);
64
            $user->setPassword($encoder->encodePassword($password, $user->getSalt()));
65
            $user->eraseCredentials();
66
        }
67
    }
68
69
    protected function getEncoder(UserInterface $user): PasswordEncoderInterface
70
    {
71
        return $this->encoderFactory->getEncoder($user);
72
    }
73
}
74