forked from marein/php-gaming-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPublishStoredEventsToMessageBrokerSubscriber.php
64 lines (56 loc) · 2.2 KB
/
PublishStoredEventsToMessageBrokerSubscriber.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
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types=1);
namespace Gaming\Chat\Infrastructure\Messaging;
use Gaming\Chat\Application\Event\ChatInitiated;
use Gaming\Chat\Application\Event\MessageWritten;
use Gaming\Common\Domain\DomainEvent;
use Gaming\Common\EventStore\StoredEvent;
use Gaming\Common\EventStore\StoredEventSubscriber;
use Gaming\Common\MessageBroker\Model\Message\Message;
use Gaming\Common\MessageBroker\Model\Message\Name;
use Gaming\Common\MessageBroker\Publisher;
use Gaming\Common\Normalizer\Normalizer;
use RuntimeException;
final class PublishStoredEventsToMessageBrokerSubscriber implements StoredEventSubscriber
{
public function __construct(
private readonly Publisher $publisher,
private readonly Normalizer $normalizer
) {
}
public function handle(StoredEvent $storedEvent): void
{
$domainEvent = $storedEvent->domainEvent();
// We should definitely filter the events we are going to publish,
// since that belongs to our public interface for the other contexts.
// However, it's not done for simplicity in this sample project.
// We could
// * publish specific messages by name.
// * filter out specific properties in the payload.
// * translate when the properties for an event in the payload changed.
//
// We could use a strong message format like json schema, protobuf etc. to have
// a clearly defined interface with other domains.
$this->publisher->send(
new Message(
new Name('Chat', $this->nameFromDomainEvent($domainEvent)),
json_encode(
$this->normalizer->normalize($domainEvent, $domainEvent::class),
JSON_THROW_ON_ERROR
)
)
);
}
public function commit(): void
{
$this->publisher->flush();
}
private function nameFromDomainEvent(DomainEvent $domainEvent): string
{
return match ($domainEvent::class) {
ChatInitiated::class => 'ChatInitiated',
MessageWritten::class => 'MessageWritten',
default => throw new RuntimeException($domainEvent::class . ' must be handled.')
};
}
}