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

UserEntityEventListener   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 40
ccs 20
cts 20
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A prePersist() 0 4 1
A preUpdate() 0 4 1
A process() 0 10 2
A changePassword() 0 9 2
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
}