diff --git a/src/StoredEvents/StoredEvent.php b/src/StoredEvents/StoredEvent.php index 5be24ddf..46cb4fa5 100644 --- a/src/StoredEvents/StoredEvent.php +++ b/src/StoredEvents/StoredEvent.php @@ -104,7 +104,7 @@ protected function shouldDispatchJob(): bool /** @var \Spatie\EventSourcing\EventHandlers\EventHandlerCollection $eventHandlers */ $eventHandlers = Projectionist::allEventHandlers(); - return $eventHandlers->asyncEventHandlers()->count() > 0; + return $eventHandlers->forEvent($this)->asyncEventHandlers()->isNotEmpty(); } protected function instantiateEvent(?ShouldBeStored $originalEvent): void diff --git a/tests/EventSubscriberTest.php b/tests/EventSubscriberTest.php index 0ad210da..7b2c75fd 100644 --- a/tests/EventSubscriberTest.php +++ b/tests/EventSubscriberTest.php @@ -2,6 +2,7 @@ namespace Spatie\EventSourcing\Tests; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Queue; @@ -10,6 +11,7 @@ use function PHPUnit\Framework\assertEquals; use function PHPUnit\Framework\assertInstanceOf; +use Spatie\EventSourcing\EventHandlers\Projectors\Projector; use Spatie\EventSourcing\Facades\Projectionist; use Spatie\EventSourcing\StoredEvents\HandleStoredEventJob; use Spatie\EventSourcing\StoredEvents\Models\EloquentStoredEvent; @@ -191,3 +193,29 @@ Queue::assertPushedOn('testQueue', HandleStoredEventJob::class); }); + +it('only queues event if event has async handler', function () { + Bus::fake(); + + $syncProjector = new class extends Projector { + public function onMoneyAddedEvent(MoneyAddedEvent $event) + { + } + }; + + $asyncProjector = new class extends Projector implements ShouldQueue { + public function onMoneySubtractedEvent(MoneySubtractedEvent $event) + { + } + }; + + Projectionist::addProjectors([$syncProjector, $asyncProjector]); + + event(new MoneyAddedEvent($this->account, 1234)); + + Bus::assertNotDispatched(HandleStoredEventJob::class); + + event(new MoneySubtractedEvent($this->account, 1234)); + + Bus::assertDispatched(HandleStoredEventJob::class); +}); diff --git a/tests/TestClasses/Projectors/QueuedProjector.php b/tests/TestClasses/Projectors/QueuedProjector.php index 504186ea..f151fa98 100644 --- a/tests/TestClasses/Projectors/QueuedProjector.php +++ b/tests/TestClasses/Projectors/QueuedProjector.php @@ -3,7 +3,11 @@ namespace Spatie\EventSourcing\Tests\TestClasses\Projectors; use Illuminate\Contracts\Queue\ShouldQueue; +use Spatie\EventSourcing\Tests\TestClasses\Events\MoneyAddedEventWithQueueOverride; class QueuedProjector extends BalanceProjector implements ShouldQueue { + public function onMoneyAddedEventWithQueueOverride(MoneyAddedEventWithQueueOverride $event) + { + } }