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

MailJob   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
wmc 6
eloc 15
c 0
b 0
f 0
dl 0
loc 41
ccs 14
cts 15
cp 0.9333
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A handle() 0 27 5
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