Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
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 | |
| 8 | declare(strict_types=1); |
| 9 | |
| 10 | use Phexium\Plugin\CommandBus\Adapter\TransactionalCommandBus; |
| 11 | use Phexium\Plugin\Transaction\Adapter\InMemoryTransaction; |
| 12 | use Tests\Phexium\Fake\Application\Command\Command as FakeCommand; |
| 13 | use Tests\Phexium\Fake\Plugin\CommandBus\CommandBus as FakeCommandBus; |
| 14 | use Tests\Phexium\Fake\Plugin\CommandBus\CommandBusThatThrows; |
| 15 | use Tests\Phexium\Fake\Plugin\Transaction\Transaction as FakeTransaction; |
| 16 | |
| 17 | test('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 | |
| 29 | test('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 | |
| 40 | test('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 | }); |