forked from marein/php-gaming-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFollowEventStoreDispatcher.php
54 lines (42 loc) · 1.64 KB
/
FollowEventStoreDispatcher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace Gaming\Common\EventStore;
use Gaming\Common\EventStore\Exception\EventStoreException;
use Gaming\Common\EventStore\Exception\FailedRetrieveMostRecentPublishedStoredEventIdException;
use Gaming\Common\EventStore\Exception\FailedTrackMostRecentPublishedStoredEventIdException;
use InvalidArgumentException;
final class FollowEventStoreDispatcher
{
public function __construct(
private readonly StoredEventSubscriber $storedEventSubscriber,
private readonly EventStorePointer $eventStorePointer,
private readonly PollableEventStore $pollableEventStore
) {
}
/**
* @throws EventStoreException
* @throws FailedRetrieveMostRecentPublishedStoredEventIdException
* @throws FailedTrackMostRecentPublishedStoredEventIdException
*/
public function dispatch(int $batchSize): int
{
if ($batchSize < 1) {
throw new InvalidArgumentException('batchSize must be greater than 0');
}
$lastStoredEventId = $this->eventStorePointer->retrieveMostRecentPublishedStoredEventId();
$storedEvents = $this->pollableEventStore->since(
$lastStoredEventId,
$batchSize
);
if (count($storedEvents) === 0) {
return 0;
}
foreach ($storedEvents as $storedEvent) {
$this->storedEventSubscriber->handle($storedEvent);
}
$this->storedEventSubscriber->commit();
$lastStoredEventId = end($storedEvents)->id();
$this->eventStorePointer->trackMostRecentPublishedStoredEventId($lastStoredEventId);
return count($storedEvents);
}
}