Completed
Push — master ( c9d345...34b48c )
by Valentyn
03:02 queued 01:25
created

UserEntityEventListener::preUpdate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace App\EventListener\User;
5
6
use App\Entity\User;
7
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
8
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
9
10
class UserEntityEventListener
11
{
12
    private $userPasswordEncoder;
13
14 19
    public function __construct(UserPasswordEncoderInterface $userPasswordEncoder)
15
    {
16 19
        $this->userPasswordEncoder = $userPasswordEncoder;
17 19
    }
18
19 8
    public function prePersist(LifecycleEventArgs $event): void
20
    {
21 8
        $this->process($event);
22 8
    }
23
24 1
    public function preUpdate(LifecycleEventArgs $event): void
25
    {
26 1
        $this->process($event);
27 1
    }
28
29 9
    private function process(LifecycleEventArgs $event): void
30
    {
31
        // Get user entity object
32 9
        $user = $event->getObject();
33
34
        // Valid user so lets change password
35 9
        if ($user instanceof User) {
36 6
            $this->changePassword($user);
37
        }
38 9
    }
39
40 6
    private function changePassword(User $user): void
41
    {
42 6
        $plainPassword = $user->getPlainPassword();
43
44 6
        if (!empty($plainPassword)) {
45 5
            $user->setPassword($plainPassword, $this->userPasswordEncoder);
46 5
            $user->eraseCredentials();
47
        }
48
    }
49
}