diff --git a/src/AggregateRoots/AggregateRoot.php b/src/AggregateRoots/AggregateRoot.php index ef2d2e69..d982f50a 100644 --- a/src/AggregateRoots/AggregateRoot.php +++ b/src/AggregateRoots/AggregateRoot.php @@ -138,6 +138,16 @@ public function recordConcurrently(ShouldBeStored $domainEvent, bool|callable $a public function persist(): static { + foreach ($this->recordedEvents as $i => $recordedEvent) { + $concurrencyCheck = $this->concurrencyChecks[$i]; + + if (is_null($concurrencyCheck)) { + continue; + } + + $concurrencyCheck($this); + } + $storedEvents = $this->persistWithoutApplyingToEventHandlers(); if ($this->handleEvents) { diff --git a/tests/AggregateRootTest.php b/tests/AggregateRootTest.php index e6867ef0..ab71765f 100644 --- a/tests/AggregateRootTest.php +++ b/tests/AggregateRootTest.php @@ -369,6 +369,12 @@ })->throws(CouldNotPersistAggregate::class); it('also validates concurrency checks before persisting', function () { + $aggregateRoot = AccountAggregateRootWithConcurrency::retrieve($this->aggregateUuid); + $aggregateRoot->removeMoney(100); + $aggregateRoot->persist(); +})->throws(Exception::class, 'Insufficient balance'); + +it('also validates concurrency checks before persisting concurrently', function () { $aggregateRoot = AccountAggregateRootWithConcurrency::retrieve($this->aggregateUuid); $aggregateRoot->removeMoney(100); $aggregateRoot->persistConcurrently();