Skip to content

Commit

Permalink
Merge pull request #381 from 27pchrisl/use-last-snapshot
Browse files Browse the repository at this point in the history
Use the snapshot with the highest ID
  • Loading branch information
freekmurze authored Dec 22, 2022
2 parents 96659e1 + 1cf6bb4 commit da4ebb2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Snapshots/EloquentSnapshotRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function retrieve(string $aggregateUuid): ?Snapshot
/** @var \Illuminate\Database\Query\Builder $query */
$query = $this->snapshotModel::query();

if ($snapshot = $query->latest()->uuid($aggregateUuid)->first()) {
if ($snapshot = $query->orderByDesc('id')->uuid($aggregateUuid)->first()) {
return $snapshot->toSnapshot();
}

Expand Down
23 changes: 23 additions & 0 deletions tests/AggregateRootTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

use Carbon\CarbonImmutable;
use Exception;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Mail;

use function PHPUnit\Framework\assertCount;
use function PHPUnit\Framework\assertEmpty;
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertInstanceOf;
use function PHPUnit\Framework\assertTrue;
Expand Down Expand Up @@ -377,3 +379,24 @@

assertTrue($now->eq($event->createdAt()));
});

it('should always retrieve the last snapshot', function () {
Carbon::setTestNow();

/** @var \Spatie\EventSourcing\Tests\TestClasses\AggregateRoots\AccountAggregateRoot $aggregateRoot */
$aggregateRoot = AccountAggregateRoot::retrieve($this->aggregateUuid);

$aggregateRoot
->addMoney(100)
->persist();

$aggregateRoot->snapshot();
$aggregateRoot->addMoney(100)->persist();
$aggregateRoot->snapshot();

$aggregateRootRetrieved = AccountAggregateRoot::retrieve($this->aggregateUuid);

assertEmpty($aggregateRootRetrieved->getAppliedEvents());
assertEquals(2, $aggregateRootRetrieved->aggregateVersion);
assertEquals(200, $aggregateRootRetrieved->balance);
});

0 comments on commit da4ebb2

Please sign in to comment.