Lines 100.00% 24 / 24
Methods 100.00% 2 / 2
Classes 100.00% 1 / 1
Covered by tests of size
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 __invoke 100.00% 23 / 23 100.00% 1 / 1 13
27final readonly class SendMailHandler
28{
29    public function __construct(
30        private Configuration $configuration,
31        private ?Closure $mailFactory = null,
32    ) {
33    }
34
35    public function __invoke(SendMailMessage $message): void
36    {
37        $mail = null;
38        if ($this->mailFactory instanceof Closure) {
39            $createdMail = ($this->mailFactory)();
40            if ($createdMail instanceof Mail) {
41                $mail = $createdMail;
42            }
43        }
44
45        $mail ??= new Mail($this->configuration);
46
47        $envelope = $message->metadata['envelope'] ?? null;
48        if (
49            is_array($envelope)
50            && array_key_exists('recipients', $envelope)
51            && array_key_exists('headers', $envelope)
52            && array_key_exists('body', $envelope)
53            && is_string($envelope['recipients'])
54            && is_array($envelope['headers'])
55            && is_string($envelope['body'])
56        ) {
57            $headers = [];
58            foreach ($envelope['headers'] as $headerName => $headerValue) {
59                $headers[(string) $headerName] = is_int($headerValue) || is_string($headerValue) ? $headerValue : null;
60            }
61
62            $mail->sendPreparedEnvelope($envelope['recipients'], $headers, $envelope['body']);
63
64            return;
65        }
66
67        $mail->addTo($message->recipient);
68        $mail->subject = $message->subject;
69        $mail->message = $message->body;
70        $mail->send(forceSynchronousDelivery: true);
71    }
72}