diff --git a/src/StoredEvents/Repositories/EloquentStoredEventRepository.php b/src/StoredEvents/Repositories/EloquentStoredEventRepository.php index a58305c2..f81046c1 100644 --- a/src/StoredEvents/Repositories/EloquentStoredEventRepository.php +++ b/src/StoredEvents/Repositories/EloquentStoredEventRepository.php @@ -93,10 +93,9 @@ public function persist(ShouldBeStored $event, string $uuid = null): StoredEvent throw new InvalidStoredEvent(); } + $serializerClass = EventSerializer::class; if ($serializerAttribute = $reflectionClass->getAttributes(EventSerializerAttribute::class)[0] ?? null) { - $serializerClass = ($serializerAttribute->newInstance())->serializerClass; - } else { - $serializerClass = EventSerializer::class; + $serializerClass = $serializerAttribute->newInstance()->serializerClass; } $eloquentStoredEvent->setRawAttributes([ diff --git a/tests/EloquentStoredEventRepositoryTest.php b/tests/EloquentStoredEventRepositoryTest.php index f1a313d8..4280bfe4 100644 --- a/tests/EloquentStoredEventRepositoryTest.php +++ b/tests/EloquentStoredEventRepositoryTest.php @@ -8,6 +8,7 @@ use Spatie\EventSourcing\StoredEvents\Repositories\EloquentStoredEventRepository; use Spatie\EventSourcing\Tests\TestClasses\AggregateRoots\AccountAggregateRoot; use Spatie\EventSourcing\Tests\TestClasses\AggregateRoots\StorableEvents\MoneyAdded; +use Spatie\EventSourcing\Tests\TestClasses\Events\EventWithCustomSerializer; it('can get the latest version id for a given aggregate uuid', function () { $eloquentStoredEventRepository = new EloquentStoredEventRepository(); @@ -37,3 +38,13 @@ assertSame($originalEvent, $storedEvent->event); }); + +it('uses the custom serializer if one is set', function () { + $eloquentStoredEventRepository = app(EloquentStoredEventRepository::class); + + $originalEvent = new EventWithCustomSerializer('default message'); + $storedEvent = $eloquentStoredEventRepository->persist($originalEvent, 'uuid-1', 1); + + $eventFromDatabase = $eloquentStoredEventRepository->find($storedEvent->id)->event; + assertSame('message set by custom serializer', $eventFromDatabase->message); +})->only(); diff --git a/tests/TestClasses/EventSerializer/DummySerializer.php b/tests/TestClasses/EventSerializer/DummySerializer.php new file mode 100644 index 00000000..7f12eb2b --- /dev/null +++ b/tests/TestClasses/EventSerializer/DummySerializer.php @@ -0,0 +1,15 @@ +message = $message; + } +}