Passed
Push — master ( a2340d...9d7d2b )
by butschster
06:32
created

MailJob::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 6
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 4
crap 1
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)) {
0 ignored issues
show
introduced by
The condition is_string($payload) is always false.
Loading history...
34 6
            $payload = \json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
35
        }
36
37 6
        if (!\is_array($payload)) {
0 ignored issues
show
introduced by
The condition is_array($payload) is always true.
Loading history...
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