-
Notifications
You must be signed in to change notification settings - Fork 1
/
DoctrineUuidV4MessageRepository.php
201 lines (172 loc) · 7.44 KB
/
DoctrineUuidV4MessageRepository.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
<?php
namespace EventSauce\MessageRepository\DoctrineMessageRepository;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use EventSauce\EventSourcing\AggregateRootId;
use EventSauce\EventSourcing\Header;
use EventSauce\EventSourcing\Message;
use EventSauce\EventSourcing\MessageRepository;
use EventSauce\EventSourcing\OffsetCursor;
use EventSauce\EventSourcing\PaginationCursor;
use EventSauce\EventSourcing\Serialization\MessageSerializer;
use EventSauce\EventSourcing\UnableToPersistMessages;
use EventSauce\EventSourcing\UnableToRetrieveMessages;
use EventSauce\MessageRepository\TableSchema\DefaultTableSchema;
use EventSauce\MessageRepository\TableSchema\TableSchema;
use EventSauce\UuidEncoding\BinaryUuidEncoder;
use EventSauce\UuidEncoding\UuidEncoder;
use Generator;
use LogicException;
use Ramsey\Uuid\Uuid;
use Throwable;
use function array_keys;
use function array_map;
use function array_merge;
use function count;
use function get_class;
use function implode;
use function json_decode;
use function json_encode;
use function sprintf;
/**
* @deprecated Will be removed in 2.0.0
* @see DoctrineMessageRepository
*/
class DoctrineUuidV4MessageRepository implements MessageRepository
{
private TableSchema $tableSchema;
private UuidEncoder $uuidEncoder;
public function __construct(
private Connection $connection,
private string $tableName,
private MessageSerializer $serializer,
private int $jsonEncodeOptions = 0,
?TableSchema $tableSchema = null,
?UuidEncoder $uuidEncoder = null,
) {
$this->tableSchema = $tableSchema ?? new DefaultTableSchema();
$this->uuidEncoder = $uuidEncoder ?? new BinaryUuidEncoder();
}
public function persist(Message ...$messages): void
{
if (count($messages) === 0) {
return;
}
$insertColumns = [
$this->tableSchema->eventIdColumn(),
$this->tableSchema->aggregateRootIdColumn(),
$this->tableSchema->versionColumn(),
$this->tableSchema->payloadColumn(),
...array_keys($additionalColumns = $this->tableSchema->additionalColumns()),
];
$insertValues = [];
$insertParameters = [];
foreach ($messages as $index => $message) {
$payload = $this->serializer->serializeMessage($message);
$payload['headers'][Header::EVENT_ID] ??= Uuid::uuid4()->toString();
$messageParameters = [
$this->indexParameter('event_id', $index) => $this->uuidEncoder->encodeString($payload['headers'][Header::EVENT_ID]),
$this->indexParameter('aggregate_root_id', $index) => $this->uuidEncoder->encodeString($payload['headers'][Header::AGGREGATE_ROOT_ID]),
$this->indexParameter('version', $index) => $payload['headers'][Header::AGGREGATE_ROOT_VERSION] ?? 0,
$this->indexParameter('payload', $index) => json_encode($payload, $this->jsonEncodeOptions),
];
foreach ($additionalColumns as $column => $header) {
$messageParameters[$this->indexParameter($column, $index)] = $payload['headers'][$header];
}
// Creates a values line like: (:event_id_1, :aggregate_root_id_1, ...)
$insertValues[] = implode(', ', $this->formatNamedParameters(array_keys($messageParameters)));
// Flatten the message parameters into the query parameters
$insertParameters = array_merge($insertParameters, $messageParameters);
}
$insertQuery = sprintf(
"INSERT INTO %s (%s) VALUES\n(%s)",
$this->tableName,
implode(', ', $insertColumns),
implode("),\n(", $insertValues),
);
try {
$this->connection->executeStatement($insertQuery, $insertParameters);
} catch (Throwable $exception) {
throw UnableToPersistMessages::dueTo('', $exception);
}
}
private function indexParameter(string $name, int $index): string
{
return $name . '_' . $index;
}
private function formatNamedParameters(array $parameters): array
{
return array_map(static fn (string $name) => ':' . $name, $parameters);
}
public function retrieveAll(AggregateRootId $id): Generator
{
$builder = $this->createQueryBuilder();
$builder->where(sprintf('%s = :aggregate_root_id', $this->tableSchema->aggregateRootIdColumn()));
$builder->setParameter('aggregate_root_id', $this->uuidEncoder->encodeString($id->toString()));
try {
return $this->yieldMessagesFromPayloads($builder->executeQuery()->iterateColumn());
} catch (Throwable $exception) {
throw UnableToRetrieveMessages::dueTo('', $exception);
}
}
/**
* @psalm-return Generator<Message>
*/
public function retrieveAllAfterVersion(AggregateRootId $id, int $aggregateRootVersion): Generator
{
$builder = $this->createQueryBuilder();
$builder->where(sprintf('%s = :aggregate_root_id', $this->tableSchema->aggregateRootIdColumn()));
$builder->andWhere(sprintf('%s > :version', $this->tableSchema->versionColumn()));
$builder->setParameter('aggregate_root_id', $this->uuidEncoder->encodeString($id->toString()));
$builder->setParameter('version', $aggregateRootVersion);
try {
return $this->yieldMessagesFromPayloads($builder->executeQuery()->iterateColumn());
} catch (Throwable $exception) {
throw UnableToRetrieveMessages::dueTo('', $exception);
}
}
private function createQueryBuilder(): QueryBuilder
{
$builder = $this->connection->createQueryBuilder();
$builder->select($this->tableSchema->payloadColumn());
$builder->from($this->tableName);
$builder->orderBy($this->tableSchema->versionColumn(), 'ASC');
return $builder;
}
/**
* @psalm-return Generator<Message>
*/
private function yieldMessagesFromPayloads(iterable $payloads): Generator
{
foreach ($payloads as $payload) {
yield $message = $this->serializer->unserializePayload(json_decode($payload, true));
}
return isset($message)
? $message->header(Header::AGGREGATE_ROOT_VERSION) ?: 0
: 0;
}
public function paginate(PaginationCursor $cursor): Generator
{
if ( ! $cursor instanceof OffsetCursor) {
throw new LogicException(sprintf('Wrong cursor type used, expected %s, received %s', OffsetCursor::class, get_class($cursor)));
}
$numberOfMessages = 0;
$builder = $this->connection->createQueryBuilder();
$builder->select($this->tableSchema->payloadColumn());
$builder->from($this->tableName);
$incrementalIdColumn = $this->tableSchema->incrementalIdColumn();
$builder->orderBy($incrementalIdColumn, 'ASC');
$builder->setMaxResults($cursor->limit());
$builder->where($incrementalIdColumn . ' > :id');
$builder->setParameter('id', $cursor->offset());
try {
foreach ($builder->executeQuery()->iterateColumn() as $payload) {
$numberOfMessages++;
yield $this->serializer->unserializePayload(json_decode($payload, true));
}
} catch (Throwable $exception) {
throw UnableToRetrieveMessages::dueTo($exception->getMessage(), $exception);
}
return $cursor->plusOffset($numberOfMessages);
}
}