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

UserEventListener::onPostWrite()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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