Repository navigation
Expand file tree
/
Copy pathAbstractUserEmailFactory.php
More file actions
199 lines (164 loc) · 7.31 KB
/
Copy pathAbstractUserEmailFactory.php
File metadata and controls
199 lines (164 loc) · 7.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
<?php
/*
* This file is part of the Silverback API Components Bundle Project
*
* (c) Daniel West <daniel@silverback.is>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silverback\ApiComponentsBundle\Factory\User\Mailer;
use Psr\Container\ContainerInterface;
use Silverback\ApiComponentsBundle\Entity\User\AbstractUser;
use Silverback\ApiComponentsBundle\Event\UserEmailMessageEvent;
use Silverback\ApiComponentsBundle\Exception\BadMethodCallException;
use Silverback\ApiComponentsBundle\Exception\InvalidArgumentException;
use Silverback\ApiComponentsBundle\Exception\RfcComplianceException;
use Silverback\ApiComponentsBundle\Exception\UnexpectedValueException;
use Silverback\ApiComponentsBundle\Helper\RefererUrlResolver;
use Silverback\ApiComponentsBundle\Helper\RelativeUrlPath;
use Silverback\ApiComponentsBundle\Security\TokenGenerator;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Exception\RfcComplianceException as SymfonyRfcComplianceException;
use Symfony\Component\Mime\RawMessage;
use Symfony\Contracts\Service\ResetInterface;
/**
* @author Daniel West <daniel@silverback.is>
*/
abstract class AbstractUserEmailFactory implements ResetInterface
{
public const MESSAGE_ID_PREFIX = 'xx';
protected ContainerInterface $container;
private EventDispatcherInterface $eventDispatcher;
protected string $subject;
protected bool $enabled;
protected ?string $defaultRedirectPath;
protected ?string $redirectPathQueryKey;
protected array $emailContext;
protected ?RawMessage $message;
private ?AbstractUser $user = null;
public function __construct(ContainerInterface $container, EventDispatcherInterface $eventDispatcher, string $subject, bool $enabled = true, ?string $defaultRedirectPath = null, ?string $redirectPathQueryKey = null, array $emailContext = [])
{
$this->container = $container;
$this->eventDispatcher = $eventDispatcher;
$this->subject = $subject;
$this->enabled = $enabled;
$this->emailContext = $emailContext;
$this->defaultRedirectPath = $defaultRedirectPath;
$this->redirectPathQueryKey = $redirectPathQueryKey;
}
protected static function getContextKeys(): ?array
{
return [
'website_name',
'user',
];
}
public function reset(): void
{
$this->user = null;
}
protected function initUser(AbstractUser $user): void
{
if (!$user->getUsername()) {
throw new InvalidArgumentException('The user must have a username set to send them any email');
}
if (!$user->getEmailAddress()) {
throw new InvalidArgumentException('The user must have an email address set to send them any email');
}
$this->user = $user;
}
protected function createEmailMessage(array $context = []): ?TemplatedEmail
{
if (!$this->enabled) {
return null;
}
if (!isset($this->user)) {
throw new BadMethodCallException('You must call the method `initUser` before `createEmailMessage`');
}
try {
$toEmailAddress = Address::create((string) $this->user->getEmailAddress());
} catch (SymfonyRfcComplianceException $exception) {
$exception = new RfcComplianceException($exception->getMessage());
throw $exception;
}
$context = array_replace_recursive(
[
'user' => $this->user,
],
$this->emailContext,
$context
);
$this->validateContext($context);
$twig = $this->container->get('twig');
$template = $twig->createTemplate($this->subject);
$subject = $template->render($context);
$email = (new TemplatedEmail())
->to($toEmailAddress)
->subject($subject)
->htmlTemplate('@SilverbackApiComponents/emails/' . $this->getTemplate())
->context($context);
$event = new UserEmailMessageEvent(static::class, $email);
$this->eventDispatcher->dispatch($event);
$email->getHeaders()->addTextHeader('X-Message-ID', \sprintf('%s-%s', static::MESSAGE_ID_PREFIX, TokenGenerator::generateToken()));
return $event->getEmail();
}
protected function getTokenUrl(string $token, string $username, ?string $newEmail = null): string
{
if (null === $this->defaultRedirectPath && null === $this->redirectPathQueryKey) {
throw new InvalidArgumentException('The `defaultRedirectPath` or `redirectPathQueryKey` must be set');
}
$variables = [
'token' => $token,
'username' => $username,
'new_email' => $newEmail,
];
$requestedPath = $this->getRequestedRedirectPath();
if (null !== $requestedPath && null !== ($path = RelativeUrlPath::fromRequestValue($this->populatePathVariables($requestedPath, $variables)))) {
return $this->container->get(RefererUrlResolver::class)->getAbsoluteUrl($path);
}
if (null === $this->defaultRedirectPath) {
throw new UnexpectedValueException(\sprintf('The querystring key `%s` could not be found in the request to generate a token URL', $this->redirectPathQueryKey));
}
return $this->getConfiguredUrl($this->populatePathVariables($this->defaultRedirectPath, $variables));
}
protected function getConfiguredUrl(string $pathOrUrl): string
{
if (str_contains($pathOrUrl, '://') || str_starts_with($pathOrUrl, '//')) {
return $pathOrUrl;
}
return $this->container->get(RefererUrlResolver::class)->getAbsoluteUrl(RelativeUrlPath::fromConfiguration($pathOrUrl));
}
private function getRequestedRedirectPath(): ?string
{
if (null === $this->redirectPathQueryKey) {
return null;
}
$request = $this->container->get(RequestStack::class)->getMainRequest();
$value = $request?->query->all()[$this->redirectPathQueryKey] ?? null;
return \is_string($value) ? $value : null;
}
private function populatePathVariables(string $path, array $variables): string
{
preg_match_all('/{{[\s]*(\w+)[\s]*}}/', $path, $matches);
foreach ($matches[0] as $matchIndex => $fullMatch) {
if (\array_key_exists($varKey = $matches[1][$matchIndex], $variables) && null !== $variables[$varKey]) {
$path = str_replace($fullMatch, rawurlencode($variables[$varKey]), $path);
}
}
return $path;
}
private function validateContext(array $context): void
{
$contextKeys = static::getContextKeys();
$keys = array_keys($context);
if (\count($differences = array_diff($contextKeys, $keys))) {
throw new InvalidArgumentException(\sprintf('You have not specified required context key(s) for the user email factory factory `%s` (expected: `%s`)', static::class, implode('`, `', $differences)));
}
}
abstract public function create(AbstractUser $user, array $context = []): ?RawMessage;
abstract protected function getTemplate(): string;
}