|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spiral\SendIt; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\EventDispatcher\EventDispatcherInterface; |
|
8
|
|
|
use Spiral\Queue\Exception\InvalidArgumentException; |
|
9
|
|
|
use Spiral\Queue\HandlerInterface; |
|
10
|
|
|
use Spiral\SendIt\Config\MailerConfig; |
|
11
|
|
|
use Spiral\SendIt\Event\MessageNotSent; |
|
12
|
|
|
use Spiral\SendIt\Event\MessageSent; |
|
13
|
|
|
use Symfony\Component\Mailer\Exception\TransportExceptionInterface; |
|
14
|
|
|
use Symfony\Component\Mailer\MailerInterface as SymfonyMailer; |
|
15
|
|
|
use Symfony\Component\Mime\Address; |
|
16
|
|
|
|
|
17
|
|
|
final class MailJob implements HandlerInterface |
|
18
|
|
|
{ |
|
19
|
7 |
|
public function __construct( |
|
20
|
|
|
private readonly MailerConfig $config, |
|
21
|
|
|
private readonly SymfonyMailer $mailer, |
|
22
|
|
|
private readonly RendererInterface $renderer, |
|
23
|
|
|
private readonly ?EventDispatcherInterface $dispatcher = null |
|
24
|
|
|
) { |
|
25
|
7 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @throws TransportExceptionInterface |
|
29
|
|
|
* @throws InvalidArgumentException |
|
30
|
|
|
*/ |
|
31
|
6 |
|
public function handle(string $name, string $id, string|array $payload): void |
|
32
|
|
|
{ |
|
33
|
6 |
|
if (\is_string($payload)) { |
|
|
|
|
|
|
34
|
6 |
|
$payload = \json_decode($payload, true, 512, JSON_THROW_ON_ERROR); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
6 |
|
if (!\is_array($payload)) { |
|
|
|
|
|
|
38
|
|
|
throw new InvalidArgumentException('Mail job payload should be an array.'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
6 |
|
$message = MessageSerializer::unpack($payload); |
|
42
|
|
|
|
|
43
|
6 |
|
$email = $this->renderer->render($message); |
|
44
|
|
|
|
|
45
|
5 |
|
if ($email->getFrom() === []) { |
|
46
|
5 |
|
$email->from(Address::create($this->config->getFromAddress())); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
try { |
|
50
|
5 |
|
$this->mailer->send($email); |
|
51
|
2 |
|
} catch (TransportExceptionInterface $e) { |
|
52
|
2 |
|
$this->dispatcher?->dispatch(new MessageNotSent($email, $e)); |
|
53
|
|
|
|
|
54
|
|
|
throw $e; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
3 |
|
$this->dispatcher?->dispatch(new MessageSent($email)); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|