-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathEmailTask.php
More file actions
293 lines (251 loc) · 8.7 KB
/
Copy pathEmailTask.php
File metadata and controls
293 lines (251 loc) · 8.7 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
declare(strict_types=1);
namespace Queue\Queue\Task;
use Cake\Core\Configure;
use Cake\Log\Log;
use Cake\Mailer\Mailer;
use Cake\Mailer\Message;
use Cake\Mailer\TransportFactory;
use Psr\Log\LoggerInterface;
use Queue\Console\Io;
use Queue\Model\QueueException;
use Queue\Queue\AddFromBackendInterface;
use Queue\Queue\AddInterface;
use Queue\Queue\Task;
use Throwable;
/**
* A convenience task ready to use for asynchronously sending basic emails.
* Uses basic Message object.
*
* Especially useful is the fact that sending is auto-retried as per your config.
* Will not drop the email if successfully sent, you can decide to even retry manually again afterwards.
*
* @author Mark Scherer
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class EmailTask extends Task implements AddInterface, AddFromBackendInterface {
public ?int $timeout = 60;
public Mailer $mailer;
public Message $message;
/**
* List of default variables for Email class.
*
* @var array<string, mixed>
*/
protected array $defaults = [];
/**
* @param \Queue\Console\Io|null $io IO
* @param \Psr\Log\LoggerInterface|null $logger
*/
public function __construct(?Io $io = null, ?LoggerInterface $logger = null) {
parent::__construct($io, $logger);
$adminEmail = Configure::read('Config.adminEmail');
if ($adminEmail) {
$this->defaults['from'] = $adminEmail;
}
}
/**
* "Add" the task, not possible for EmailTask without adminEmail configured.
*
* @param string|null $data
*
* @return void
*/
public function add(?string $data): void {
$adminEmail = Configure::read('Config.adminEmail');
if ($adminEmail) {
$data = [
'settings' => [
'to' => $adminEmail,
'subject' => 'Test Subject',
'from' => $adminEmail,
],
'content' => 'Hello world',
];
$this->QueuedJobs->createJob('Queue.Email', $data);
$this->io->success('OK, job created for email `' . $adminEmail . '`, now run the worker');
return;
}
$this->io->warn('Queue Email Task cannot be added via Console without `Config.adminEmail` being set.');
$this->io->out('Please set this config value in your app.php Configure config. It will use this for to+from then.');
$this->io->out('Or use createJob() on the QueuedTasks Table to create a proper QueueEmail job.');
$this->io->out('The payload $data array should look something like this:');
$this->io->out(var_export([
'settings' => [
'to' => 'email@example.com',
'subject' => 'Email Subject',
'from' => 'system@example.com',
'template' => 'sometemplate',
],
'content' => 'hello world',
], true));
$this->io->out('Alternatively, you can pass the whole Mailer in `settings` key.');
}
/**
* @param \Cake\Mailer\Message $message
*
* @return array
*/
public static function serialize(Message $message): array {
return $message->__serialize();
}
/**
* @param \Cake\Mailer\Message $object
* @param array $config
*
* @return \Cake\Mailer\Message
*/
public static function unserialize(Message $object, array $config): Message {
return $object->createFromArray($config);
}
/**
* @param array<string, mixed> $data The array passed to QueuedJobsTable::createJob()
* @param int $jobId The id of the QueuedJob entity
*
* @throws \Queue\Model\QueueException
* @throws \Throwable
*
* @return void
*/
public function run(array $data, int $jobId): void {
if (!isset($data['settings'])) {
throw new QueueException('Queue Email task called without settings data.');
}
/** @var class-string<\Cake\Mailer\Message>|object|null $class */
$class = $data['class'] ?? null;
/** @var \Cake\Mailer\Message|null $object */
$object = $class ? new $class() : null;
if ($class && $object && (is_subclass_of($class, Message::class) || is_a($object, Message::class))) {
$settings = $data['settings'];
$serialized = $data['serialized'] ?? false;
if ($serialized) {
$allowedClass = is_object($class) ? $class::class : $class;
$this->message = is_array($settings) ? static::unserialize($object, $settings) : unserialize($settings, ['allowed_classes' => [$allowedClass]]);
} else {
/** @var class-string<\Cake\Mailer\Message> $class */
$this->message = new $class($settings);
}
try {
$transport = TransportFactory::get($data['transport'] ?? 'default');
$result = $transport->send($this->message);
} catch (Throwable $e) {
$error = $e->getMessage();
$error .= ' (line ' . $e->getLine() . ' in ' . $e->getFile() . ')' . PHP_EOL . $e->getTraceAsString();
Log::write('error', $error);
throw $e;
}
if (!$result) {
throw new QueueException('Could not send email.');
}
return;
}
$this->mailer = $this->getMailer();
$settings = $data['settings'] + $this->defaults;
foreach (['to', 'from', 'cc', 'bcc', 'replyTo', 'sender', 'returnPath', 'readReceipt'] as $addressMethod) {
if (!array_key_exists($addressMethod, $settings)) {
continue;
}
$setter = 'set' . ucfirst($addressMethod);
$this->mailer->{$setter}(...$this->addressArguments($settings[$addressMethod]));
unset($settings[$addressMethod]);
}
// Message body keys from a serialized Message payload use different names than
// their setter methods. Route them explicitly so the generic loop does not try
// to call nonexistent `setHtmlMessage`/`setTextMessage` on the Mailer.
if (array_key_exists('htmlMessage', $settings)) {
$this->mailer->getMessage()->setBodyHtml((string)$settings['htmlMessage']);
unset($settings['htmlMessage']);
}
if (array_key_exists('textMessage', $settings)) {
$this->mailer->getMessage()->setBodyText((string)$settings['textMessage']);
unset($settings['textMessage']);
}
// `headers` must be passed as a single positional argument — the map's string
// keys would otherwise be interpreted as named parameters under PHP 8.
if (array_key_exists('headers', $settings)) {
$this->mailer->getMessage()->setHeaders((array)$settings['headers']);
unset($settings['headers']);
}
// `appCharset` has no setter on Mailer or Message. Fall back to the Message
// charset when a dedicated `charset` value was not also provided.
if (array_key_exists('appCharset', $settings)) {
$appCharset = (string)$settings['appCharset'];
unset($settings['appCharset']);
if (!array_key_exists('charset', $settings)) {
$this->mailer->getMessage()->setCharset($appCharset);
}
}
foreach ($settings as $method => $setting) {
$setter = 'set' . ucfirst((string)$method);
if (in_array($method, ['theme', 'template', 'layout'], true)) {
call_user_func_array([$this->mailer->viewBuilder(), $setter], (array)$setting);
continue;
}
if (in_array($method, ['helper', 'helpers'], true)) {
$setter = 'add' . ucfirst($method);
call_user_func_array([$this->mailer->viewBuilder(), $setter], (array)$setting);
continue;
}
// Special handling for attachments - pass the array directly
if ($method === 'attachments') {
$this->mailer->setAttachments($setting);
continue;
}
call_user_func_array([$this->mailer, $setter], (array)$setting);
}
$this->mailer->setTransport($data['transport'] ?? 'default');
$message = null;
if (isset($data['content'])) {
$message = $data['content'];
}
if (!empty($data['vars'])) {
$this->mailer->setViewVars($data['vars']);
}
if (!empty($data['headers'])) {
if (!is_array($data['headers'])) {
throw new QueueException('Please provide headers as array.');
}
$this->mailer->getMessage()->setHeaders($data['headers']);
}
$this->mailer->deliver((string)$message);
}
/**
* Normalizes an address setting into positional arguments for setTo/setFrom/etc.
*
* List-shaped arrays are unpacked into positional arguments (matching the
* historical `call_user_func_array` behavior), while associative `email => name`
* maps are passed as a single positional argument so PHP 8 does not interpret
* their string keys as named parameters.
*
* @param mixed $setting
*
* @return array
*/
protected function addressArguments(mixed $setting): array {
if (is_array($setting) && $setting !== [] && array_is_list($setting)) {
return $setting;
}
return [$setting];
}
/**
* Check if Mail class exists and create instance
*
* @throws \Queue\Model\QueueException
*
* @return \Cake\Mailer\Mailer
*/
protected function getMailer(): Mailer {
/** @phpstan-var class-string<\Cake\Mailer\Mailer> $class */
$class = Configure::read('Queue.mailerClass');
if (!$class) {
$class = 'Tools\Mailer\Mailer';
if (!class_exists($class)) {
$class = 'Cake\Mailer\Mailer';
}
}
if (!class_exists($class)) {
throw new QueueException(sprintf('Configured mailer class `%s` in `%s` not found.', $class, static::class));
}
return new $class();
}
}