Passed
Pull Request — feature/unit-tests (#37)
by Daniel
05:39
created

AbstractUserEmailFactory::populatePathVariables()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 10
c 1
b 0
f 0
cc 3
nc 3
nop 2
crap 3
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\Factory\Mailer\User;
15
16
use Psr\Container\ContainerInterface;
17
use Silverback\ApiComponentBundle\Entity\User\AbstractUser;
18
use Silverback\ApiComponentBundle\Event\UserEmailMessageEvent;
19
use Silverback\ApiComponentBundle\Exception\BadMethodCallException;
20
use Silverback\ApiComponentBundle\Exception\InvalidArgumentException;
21
use Silverback\ApiComponentBundle\Exception\RfcComplianceException;
22
use Silverback\ApiComponentBundle\Exception\UnexpectedValueException;
23
use Silverback\ApiComponentBundle\Url\RefererUrlHelper;
24
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
25
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
26
use Symfony\Component\HttpFoundation\RequestStack;
27
use Symfony\Component\Mime\Address;
28
use Symfony\Component\Mime\Exception\RfcComplianceException as SymfonyRfcComplianceException;
29
use Symfony\Component\Mime\RawMessage;
30
use Symfony\Contracts\Service\ServiceSubscriberInterface;
31
use Twig\Environment;
32
33
/**
34
 * @author Daniel West <[email protected]>
35
 */
36
abstract class AbstractUserEmailFactory implements ServiceSubscriberInterface
37
{
38
    protected ContainerInterface $container;
39
    private EventDispatcherInterface $eventDispatcher;
40
    protected string $subject;
41
    protected bool $enabled;
42
    protected ?string $defaultRedirectPath;
43
    protected ?string $redirectPathQueryKey;
44
    protected array $emailContext;
45
    protected ?RawMessage $message;
46
    private ?AbstractUser $user;
47
48 20
    public function __construct(
49
        ContainerInterface $container,
50
        EventDispatcherInterface $eventDispatcher,
51
        string $subject,
52
        bool $enabled = true,
53
        ?string $defaultRedirectPath = null,
54
        ?string $redirectPathQueryKey = null,
55
        array $emailContext = []
56
    ) {
57 20
        $this->container = $container;
58 20
        $this->eventDispatcher = $eventDispatcher;
59 20
        $this->subject = $subject;
60 20
        $this->enabled = $enabled;
61 20
        $this->emailContext = $emailContext;
62 20
        $this->defaultRedirectPath = $defaultRedirectPath;
63 20
        $this->redirectPathQueryKey = $redirectPathQueryKey;
64 20
    }
65
66 2
    public static function getSubscribedServices(): array
67
    {
68
        return [
69 2
            RequestStack::class,
70
            RefererUrlHelper::class,
71
            Environment::class,
72
        ];
73
    }
74
75 8
    protected static function getRequiredContextKeys(): ?array
76
    {
77
        return [
78 8
            'website_name',
79
            'user',
80
        ];
81
    }
82
83 13
    protected function initUser(AbstractUser $user): void
84
    {
85 13
        if (!$user->getUsername()) {
86 1
            throw new InvalidArgumentException('The user must have a username set to send them any email');
87
        }
88
89 12
        if (!$user->getEmailAddress()) {
90 1
            throw new InvalidArgumentException('The user must have an email address set to send them any email');
91
        }
92
93 11
        $this->user = $user;
94 11
    }
95
96 11
    protected function createEmailMessage(array $context = []): ?TemplatedEmail
97
    {
98 11
        if (!$this->enabled) {
99 1
            return null;
100
        }
101
102 10
        if (!isset($this->user)) {
103 1
            throw new BadMethodCallException('You must call the method `initUser` before `createEmailMessage`');
104
        }
105
106
        try {
107 9
            $toEmailAddress = Address::fromString((string) $this->user->getEmailAddress());
0 ignored issues
show
Bug introduced by
The method getEmailAddress() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

107
            $toEmailAddress = Address::fromString((string) $this->user->/** @scrutinizer ignore-call */ getEmailAddress());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
108 1
        } catch (SymfonyRfcComplianceException $exception) {
109 1
            $exception = new RfcComplianceException($exception->getMessage());
110 1
            throw $exception;
111
        }
112
113 8
        $context = array_replace_recursive([
114 8
            'user' => $this->user,
115 8
        ], $this->emailContext, $context);
116 8
        $this->validateContext($context);
117
118 7
        $twig = $this->container->get(Environment::class);
119 7
        $template = $twig->createTemplate($this->subject);
120 7
        $subject = $template->render($context);
121
122 7
        $email = (new TemplatedEmail())
123 7
            ->to($toEmailAddress)
124 7
            ->subject($subject)
125 7
            ->htmlTemplate('@SilverbackApiComponent/emails/' . $this->getTemplate())
126 7
            ->context($context);
127
128 7
        $event = new UserEmailMessageEvent(static::class, $email);
129 7
        $this->eventDispatcher->dispatch($event);
130
131 7
        return $event->getEmail();
132
    }
133
134 7
    protected function getTokenUrl(string $token, string $username): string
135
    {
136 7
        $path = $this->populatePathVariables($this->getTokenPath(), [
137 5
            'token' => $token,
138 5
            'username' => $username,
139
        ]);
140
141 5
        $refererUrlHelper = $this->container->get(RefererUrlHelper::class);
142
143 5
        return $refererUrlHelper->getAbsoluteUrl($path);
144
    }
145
146 7
    private function getTokenPath(): string
147
    {
148 7
        if (null === $this->defaultRedirectPath && null === $this->redirectPathQueryKey) {
149 1
            throw new InvalidArgumentException('The `defaultRedirectPath` or `redirectPathQueryKey` must be set');
150
        }
151
152 6
        $requestStack = $this->container->get(RequestStack::class);
153 6
        $request = $requestStack->getMasterRequest();
154
155 6
        $path = ($request && $this->redirectPathQueryKey) ?
156 3
            $request->query->get($this->redirectPathQueryKey, $this->defaultRedirectPath) :
157 6
            $this->defaultRedirectPath;
158
159 6
        if (null === $path) {
160 1
            throw new UnexpectedValueException(sprintf('The querystring key `%s` could not be found in the request to generate a token URL', $this->redirectPathQueryKey));
161
        }
162
163 5
        return $path;
164
    }
165
166 5
    private function populatePathVariables(string $path, array $variables): string
167
    {
168 5
        preg_match_all('/{{[\s]*(\w+)[\s]*}}/', $path, $matches);
169 5
        foreach ($matches[0] as $matchIndex => $fullMatch) {
170 2
            if (\array_key_exists($varKey = $matches[1][$matchIndex], $variables)) {
171 2
                $path = str_replace($fullMatch, rawurlencode($variables[$varKey]), $path);
172
            }
173
        }
174
175 5
        return $path;
176
    }
177
178 8
    private function validateContext(array $context): void
179
    {
180 8
        $requiredKeys = self::getRequiredContextKeys();
181 8
        foreach ($requiredKeys as $requiredKey) {
182 8
            if (!\array_key_exists($requiredKey, $context)) {
183 1
                throw new InvalidArgumentException(sprintf('The context key `%s` is required to create an email message with the factory `%s`', $requiredKey, static::class));
184
            }
185
        }
186 7
    }
187
188
    abstract public function create(AbstractUser $user, array $context = []): ?RawMessage;
189
190
    abstract protected function getTemplate(): string;
191
}
192