Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
TransactionalCommandBus
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
4 / 4
6
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%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 dispatchWithTransaction
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 dispatchWithoutTransaction
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3// ╔════════════════════════════════════════════════════════════╗
4// ║ MIT Licence (#Expat) - https://opensource.org/licenses/MIT ║
5// ║ Copyright 2026 Frederic Poeydomenge <dyno@phexium.com>     ║
6// ╚════════════════════════════════════════════════════════════╝
7
8declare(strict_types=1);
9
10namespace Phexium\Plugin\CommandBus\Adapter;
11
12use Override;
13use Phexium\Application\Command\CommandInterface;
14use Phexium\Plugin\CommandBus\Port\CommandBusInterface;
15use Phexium\Plugin\Transaction\Port\TransactionInterface;
16use Throwable;
17
18final readonly class TransactionalCommandBus implements CommandBusInterface
19{
20    public function __construct(
21        private CommandBusInterface $innerCommandBus,
22        private TransactionInterface $transaction
23    ) {}
24
25    #[Override]
26    public function dispatch(CommandInterface $command): void
27    {
28        if ($this->transaction->inTransaction()) {
29            $this->dispatchWithoutTransaction($command);
30        } else {
31            $this->dispatchWithTransaction($command);
32        }
33    }
34
35    private function dispatchWithTransaction(CommandInterface $command): void
36    {
37        $this->transaction->begin();
38
39        try {
40            $this->innerCommandBus->dispatch($command);
41            $this->transaction->commit();
42        } catch (Throwable $throwable) {
43            $this->transaction->rollback();
44            throw $throwable;
45        }
46    }
47
48    private function dispatchWithoutTransaction(CommandInterface $command): void
49    {
50        $this->innerCommandBus->dispatch($command);
51    }
52}