Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
29 / 29
n/a
0 / 0
CRAP
n/a
0 / 0
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
10use Phexium\Plugin\CommandBus\Adapter\TransactionalCommandBus;
11use Phexium\Plugin\Transaction\Adapter\InMemoryTransaction;
12use Tests\Phexium\Fake\Application\Command\Command as FakeCommand;
13use Tests\Phexium\Fake\Plugin\CommandBus\CommandBus as FakeCommandBus;
14use Tests\Phexium\Fake\Plugin\CommandBus\CommandBusThatThrows;
15use Tests\Phexium\Fake\Plugin\Transaction\Transaction as FakeTransaction;
16
17test('commits on success', function (): void {
18    $innerBus = new FakeCommandBus();
19    $transaction = new FakeTransaction(new InMemoryTransaction());
20    $bus = new TransactionalCommandBus($innerBus, $transaction);
21
22    $bus->dispatch(new FakeCommand());
23
24    expect($innerBus->count())->toBe(1)
25        ->and($transaction->getCallHistory())->toBe(['begin', 'commit'])
26    ;
27});
28
29test('rollbacks on exception', function (): void {
30    $innerBus = new CommandBusThatThrows(new RuntimeException('fail'));
31    $transaction = new FakeTransaction(new InMemoryTransaction());
32    $bus = new TransactionalCommandBus($innerBus, $transaction);
33
34    expect(fn () => $bus->dispatch(new FakeCommand()))
35        ->toThrow(RuntimeException::class)
36        ->and($transaction->getCallHistory())->toBe(['begin', 'rollback'])
37    ;
38});
39
40test('skips transaction if already in transaction', function (): void {
41    $innerBus = new FakeCommandBus();
42    $realTransaction = new InMemoryTransaction();
43    $transaction = new FakeTransaction($realTransaction);
44    $bus = new TransactionalCommandBus($innerBus, $transaction);
45
46    $realTransaction->begin();
47    $bus->dispatch(new FakeCommand());
48
49    expect($innerBus->count())->toBe(1)
50        ->and($transaction->getCallHistory())->toBe([])
51    ;
52});