Passed
Push — v2 ( 0c1c16...7ee84c )
by Daniel
04:36
created

UserListener::preUpdate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\EventListener\Doctrine;
15
16
use Doctrine\ORM\Event\LifecycleEventArgs;
17
use Silverback\ApiComponentBundle\Entity\User\AbstractUser;
18
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
19
20
/**
21
 * @author Daniel West <[email protected]>
22
 */
23
class UserListener
24
{
25
    private UserPasswordEncoderInterface $passwordEncoder;
26
    private array $changeSet = [];
27
28
    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
29
    {
30
        $this->passwordEncoder = $passwordEncoder;
31
    }
32
33
    public function prePersist(AbstractUser $user): void
34
    {
35
        $this->encodePassword($user);
36
    }
37
38
    public function postPersist(): void
39
    {
40
        // send new user notification email to admin if enabled (it is enabled by default)
41
42
        // send welcome email to new user if enabled (it is enabled by default)
43
    }
44
45
    public function preUpdate(AbstractUser $user, LifecycleEventArgs $args): void
46
    {
47
        $this->encodePassword($user);
48
49
        $this->changeSet = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($user);
50
    }
51
52
    public function postUpdate(AbstractUser $user): void
53
    {
54
        if (isset($this->changeSet['enabled']) && !$this->changeSet['enabled'][0] && $user->isEnabled()) {
55
            // send notification email to user
56
        }
57
58
        if (isset($this->changeSet['username'])) {
59
            // send notification email to user
60
        }
61
62
        if (isset($this->changeSet['password'])) {
63
            // send notification email to user
64
        }
65
    }
66
67
    private function encodePassword(AbstractUser $entity): void
68
    {
69
        if (!$entity->getPlainPassword()) {
70
            return;
71
        }
72
        $encoded = $this->passwordEncoder->encodePassword(
73
            $entity,
74
            $entity->getPlainPassword()
75
        );
76
        $entity->setPassword($encoded);
77
        $entity->eraseCredentials();
78
    }
79
}
80