1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EventSauce\EventSourcing\Serialization; |
6
|
|
|
|
7
|
|
|
use EventSauce\EventSourcing\AggregateRootId; |
8
|
|
|
use EventSauce\EventSourcing\ClassNameInflector; |
9
|
|
|
use EventSauce\EventSourcing\DotSeparatedSnakeCaseInflector; |
10
|
|
|
use EventSauce\EventSourcing\Header; |
11
|
|
|
use EventSauce\EventSourcing\Message; |
12
|
|
|
|
13
|
|
|
final class ConstructingMessageSerializer implements MessageSerializer |
14
|
|
|
{ |
15
|
|
|
private ClassNameInflector $classNameInflector; |
16
|
|
|
private PayloadSerializer $payloadSerializer; |
17
|
|
|
|
18
|
|
|
public function __construct( |
19
|
|
|
ClassNameInflector $classNameInflector = null, |
20
|
|
|
PayloadSerializer $payloadSerializer = null |
21
|
|
|
) { |
22
|
|
|
$this->classNameInflector = $classNameInflector ?: new DotSeparatedSnakeCaseInflector(); |
23
|
|
|
$this->payloadSerializer = $payloadSerializer ?: new ConstructingPayloadSerializer(); |
24
|
|
|
} |
25
|
|
|
|
26
|
20 |
|
public function serializeMessage(Message $message): array |
27
|
|
|
{ |
28
|
|
|
$event = $message->event(); |
29
|
|
|
$payload = $this->payloadSerializer->serializePayload($event); |
30
|
20 |
|
$headers = $message->headers(); |
31
|
20 |
|
$aggregateRootId = $headers[Header::AGGREGATE_ROOT_ID] ?? null; |
32
|
20 |
|
|
33
|
|
|
if ($aggregateRootId instanceof AggregateRootId) { |
34
|
11 |
|
$headers[Header::AGGREGATE_ROOT_ID_TYPE] = $this->classNameInflector->instanceToType($aggregateRootId); |
35
|
|
|
$headers[Header::AGGREGATE_ROOT_ID] = $aggregateRootId->toString(); |
36
|
11 |
|
} |
37
|
11 |
|
|
38
|
11 |
|
return [ |
39
|
11 |
|
'headers' => $headers, |
40
|
|
|
'payload' => $payload, |
41
|
11 |
|
]; |
42
|
10 |
|
} |
43
|
10 |
|
|
44
|
|
|
public function unserializePayload(array $payload): Message |
45
|
|
|
{ |
46
|
|
|
if (isset($payload['headers'][Header::AGGREGATE_ROOT_ID], $payload['headers'][Header::AGGREGATE_ROOT_ID_TYPE])) { |
47
|
11 |
|
/** @var AggregateRootId $aggregateRootIdClassName */ |
48
|
11 |
|
$aggregateRootIdClassName = $this->classNameInflector->typeToClassName($payload['headers'][Header::AGGREGATE_ROOT_ID_TYPE]); |
49
|
|
|
$payload['headers'][Header::AGGREGATE_ROOT_ID] = $aggregateRootIdClassName::fromString($payload['headers'][Header::AGGREGATE_ROOT_ID]); |
50
|
|
|
} |
51
|
|
|
|
52
|
12 |
|
$className = $this->classNameInflector->typeToClassName($payload['headers'][Header::EVENT_TYPE]); |
53
|
|
|
$event = $this->payloadSerializer->unserializePayload($className, $payload['payload']); |
54
|
12 |
|
|
55
|
|
|
return new Message($event, $payload['headers']); |
56
|
10 |
|
} |
57
|
|
|
} |
58
|
|
|
|