Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
DatabaseMessageBus
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
2 / 2
3
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
 dispatch
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3/**
4 * Database-backed message bus for background jobs.
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;
21
22use phpMyFAQ\Queue\Message\QueueMessageInterface;
23use phpMyFAQ\Queue\Transport\DatabaseTransport;
24
25final readonly class DatabaseMessageBus
26{
27    public function __construct(
28        private DatabaseTransport $databaseTransport,
29    ) {
30    }
31
32    /**
33     * @param array<string, mixed> $headers
34     * @throws \JsonException
35     */
36    public function dispatch(object $message, string $queue = 'default', array $headers = []): int
37    {
38        $payload = $message instanceof QueueMessageInterface ? $message->toArray() : get_object_vars($message);
39
40        $encodedBody = json_encode([
41            'class' => $message::class,
42            'payload' => $payload,
43        ], JSON_THROW_ON_ERROR);
44
45        return $this->databaseTransport->enqueue($encodedBody, $headers, $queue);
46    }
47}