Passed
Pull Request — master (#67)
by Daniel
06:12
created

UserEventListener::postWrite()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 11
c 1
b 0
f 0
nc 17
nop 2
dl 0
loc 22
ccs 0
cts 12
cp 0
crap 56
rs 8.8333
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components 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\ApiComponentsBundle\EventListener\Api;
15
16
use Silverback\ApiComponentsBundle\Entity\User\AbstractUser;
17
use Silverback\ApiComponentsBundle\Helper\User\UserMailer;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpKernel\Event\ViewEvent;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class UserEventListener
25
{
26
    private UserMailer $userMailer;
27
28
    public function __construct(UserMailer $userMailer)
29
    {
30
        $this->userMailer = $userMailer;
31
    }
32
33
    public function onPostWrite(ViewEvent $event): void
34
    {
35
        $request = $event->getRequest();
36
        $data = $request->attributes->get('data');
37
        $previousData = $request->attributes->get('previous_data');
38
        if (
39
            empty($data) ||
40
            !$data instanceof AbstractUser ||
41
            $request->isMethod(Request::METHOD_GET) ||
42
            $request->isMethod(Request::METHOD_DELETE)
43
        ) {
44
            return;
45
        }
46
47
        $this->postWrite($data, !$request->isMethod(Request::METHOD_POST) ? $previousData : null);
48
    }
49
50
    public function postWrite(AbstractUser $user, ?AbstractUser $previousUser): void
51
    {
52
        if (!$previousUser) {
53
            $this->userMailer->sendWelcomeEmail($user);
54
55
            return;
56
        }
57
58
        if (!$previousUser->isEnabled() && $user->isEnabled()) {
59
            $this->userMailer->sendUserEnabledEmail($user);
60
        }
61
62
        if ($previousUser->getUsername() !== $user->getUsername()) {
63
            $this->userMailer->sendUsernameChangedEmail($user);
64
        }
65
66
        if ($previousUser->getPassword() !== $user->getPassword()) {
67
            $this->userMailer->sendPasswordChangedEmail($user);
68
        }
69
70
        if ($previousUser->getNewEmailAddress() !== $user->getNewEmailAddress()) {
71
            $this->userMailer->sendChangeEmailVerificationEmail($user);
72
        }
73
    }
74
}
75