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

MailJob::handle()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 27
ccs 12
cts 13
cp 0.9231
rs 9.4888
c 0
b 0
f 0
cc 5
nc 10
nop 3
crap 5.0113
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