|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace MongoDB\Laravel\Tests\Ticket; |
| 4 | + |
| 5 | +use Exception; |
| 6 | +use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; |
| 7 | +use Illuminate\Foundation\Events\Dispatchable; |
| 8 | +use Illuminate\Support\Facades\DB; |
| 9 | +use Illuminate\Support\Facades\Event; |
| 10 | +use MongoDB\Laravel\Tests\TestCase; |
| 11 | + |
| 12 | +use function event; |
| 13 | + |
| 14 | +/** |
| 15 | + * @see https://github.com/mongodb/laravel-mongodb/issues/3328 |
| 16 | + * @see https://jira.mongodb.org/browse/PHPORM-373 |
| 17 | + */ |
| 18 | +class GH3328Test extends TestCase |
| 19 | +{ |
| 20 | + public function testAfterCommitOnSuccessfulTransaction(): void |
| 21 | + { |
| 22 | + Event::fake(); |
| 23 | + |
| 24 | + try { |
| 25 | + DB::transaction(static function (): void { |
| 26 | + event(new RegularEvent()); |
| 27 | + event(new AfterCommitEvent()); |
| 28 | + }); |
| 29 | + } catch (Exception) { |
| 30 | + } |
| 31 | + |
| 32 | + Event::assertDispatched(RegularEvent::class); |
| 33 | + Event::assertDispatched(AfterCommitEvent::class); |
| 34 | + } |
| 35 | + |
| 36 | + public function testAfterCommitOnFailedTransaction(): void |
| 37 | + { |
| 38 | + Event::fake(); |
| 39 | + |
| 40 | + try { |
| 41 | + DB::transaction(static function (): void { |
| 42 | + event(new RegularEvent()); |
| 43 | + event(new AfterCommitEvent()); |
| 44 | + |
| 45 | + throw new Exception('Transaction failed; after commit event should not be dispatched'); |
| 46 | + }); |
| 47 | + } catch (Exception) { |
| 48 | + } |
| 49 | + |
| 50 | + Event::assertDispatched(RegularEvent::class); |
| 51 | + Event::assertNotDispatched(AfterCommitEvent::class); |
| 52 | + } |
| 53 | + |
| 54 | + public function testAfterCommitOnSuccessfulManualTransaction(): void |
| 55 | + { |
| 56 | + Event::fake(); |
| 57 | + |
| 58 | + DB::beginTransaction(); |
| 59 | + |
| 60 | + event(new RegularEvent()); |
| 61 | + event(new AfterCommitEvent()); |
| 62 | + |
| 63 | + DB::commit(); |
| 64 | + |
| 65 | + Event::assertDispatched(RegularEvent::class); |
| 66 | + Event::assertDispatched(AfterCommitEvent::class); |
| 67 | + } |
| 68 | + |
| 69 | + public function testAfterCommitOnUncommitedManualTransaction(): void |
| 70 | + { |
| 71 | + Event::fake(); |
| 72 | + |
| 73 | + DB::beginTransaction(); |
| 74 | + |
| 75 | + event(new RegularEvent()); |
| 76 | + event(new AfterCommitEvent()); |
| 77 | + |
| 78 | + Event::assertDispatched(RegularEvent::class); |
| 79 | + Event::assertNotDispatched(AfterCommitEvent::class); |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +class AfterCommitEvent implements ShouldDispatchAfterCommit |
| 84 | +{ |
| 85 | + use Dispatchable; |
| 86 | +} |
| 87 | + |
| 88 | +class RegularEvent |
| 89 | +{ |
| 90 | + use Dispatchable; |
| 91 | +} |
0 commit comments