1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace EventSauce\EventSourcing\Serialization; |
4
|
|
|
|
5
|
|
|
use EventSauce\EventSourcing\AggregateRootId; |
6
|
|
|
use EventSauce\EventSourcing\Event; |
7
|
|
|
use EventSauce\EventSourcing\Message; |
8
|
|
|
use EventSauce\EventSourcing\PointInTime; |
9
|
|
|
use Generator; |
10
|
|
|
|
11
|
|
|
final class ConstructingMessageSerializer implements MessageSerializer |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
private $aggregateRootIdClassName; |
17
|
|
|
|
18
|
1 |
|
public function __construct(string $aggregateRootIdClassName) |
19
|
|
|
{ |
20
|
1 |
|
$this->aggregateRootIdClassName = $aggregateRootIdClassName; |
21
|
1 |
|
} |
22
|
|
|
|
23
|
1 |
|
public function serializeMessage(Message $message): array |
24
|
|
|
{ |
25
|
1 |
|
$event = $message->event(); |
26
|
|
|
|
27
|
|
|
return [ |
28
|
1 |
|
'type' => EventType::fromEvent($event)->toEventName(), |
29
|
1 |
|
'version' => $event->eventVersion(), |
30
|
1 |
|
'aggregateRootId' => $event->aggregateRootId()->toString(), |
31
|
1 |
|
'timeOfRecording' => $event->timeOfRecording()->toString(), |
32
|
1 |
|
'metadata' => $message->metadata(), |
33
|
1 |
|
'data' => $event->toPayload(), |
34
|
|
|
]; |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
public function unserializePayload(array $payload): Generator |
38
|
|
|
{ |
39
|
|
|
/** @var Event $className */ |
40
|
1 |
|
$className = EventType::fromEventType($payload['type'])->toClassName(); |
41
|
|
|
/** @var AggregateRootId $aggregateRootIdClassName */ |
42
|
1 |
|
$aggregateRootIdClassName = $this->aggregateRootIdClassName; |
43
|
1 |
|
$event = $className::fromPayload( |
44
|
1 |
|
$payload['data'], |
45
|
1 |
|
$aggregateRootIdClassName::fromString($payload['aggregateRootId']), |
46
|
1 |
|
PointInTime::fromString($payload['timeOfRecording']) |
47
|
|
|
); |
48
|
|
|
|
49
|
1 |
|
yield new Message($event, $payload['metadata']); |
50
|
|
|
} |
51
|
|
|
} |