Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
SendMailHandler
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
2 / 2
14
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __invoke
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
13
1<?php
2
3/**
4 * Handler for queued mail messages.
5 *
6 * This Source Code Form is subject to the terms of the Mozilla Public License,
7 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
8 * obtain one at https://mozilla.org/MPL/2.0/.
9 *
10 * @package   phpMyFAQ
11 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
12 * @copyright 2026 phpMyFAQ Team
13 * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
14 * @link      https://www.phpmyfaq.de
15 * @since     2026-02-11
16 */
17
18declare(strict_types=1);
19
20namespace phpMyFAQ\Queue\Handler;
21
22use Closure;
23use phpMyFAQ\Configuration;
24use phpMyFAQ\Mail;
25use phpMyFAQ\Queue\Message\SendMailMessage;
26
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}