-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathStreamDoctrineDbalStoreAdapter.php
More file actions
93 lines (78 loc) · 2.74 KB
/
Copy pathStreamDoctrineDbalStoreAdapter.php
File metadata and controls
93 lines (78 loc) · 2.74 KB
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
<?php
namespace Patchlevel\EventSourcing\Repository\StoreAdapter;
use Patchlevel\EventSourcing\Message\Message;
use Patchlevel\EventSourcing\Store\Criteria\ArchivedCriterion;
use Patchlevel\EventSourcing\Store\Criteria\Criteria;
use Patchlevel\EventSourcing\Store\Criteria\FromPlayheadCriterion;
use Patchlevel\EventSourcing\Store\Criteria\StreamCriterion;
use Patchlevel\EventSourcing\Store\Criteria\ToPlayheadCriterion;
use Patchlevel\EventSourcing\Store\Header\PlayheadHeader;
use Patchlevel\EventSourcing\Store\Header\StreamNameHeader;
use Patchlevel\EventSourcing\Store\Stream;
use Patchlevel\EventSourcing\Store\StreamDoctrineDbalStore;
use Patchlevel\EventSourcing\Store\StreamStartHeader;
use Throwable;
final readonly class StreamDoctrineDbalStoreAdapter implements StoreAdapter
{
public function __construct(
private StreamDoctrineDbalStore $store,
) {
}
public function load(string $stream, int|null $fromPlayhead = null): Stream
{
$criteria = new Criteria(
new StreamCriterion($stream),
new ArchivedCriterion(false),
);
if ($fromPlayhead !== null) {
$criteria->add(new FromPlayheadCriterion($fromPlayhead));
}
return $this->store->load($criteria);
}
public function count(string $stream): int
{
$criteria = new Criteria(
new StreamCriterion($stream),
);
return $this->store->count($criteria);
}
/**
* @param iterable<Message> $messages
*/
public function write(string $stream, iterable $messages): void
{
$archiveTo = null;
$this->store->save(
...array_map(
static function (Message $message) use (
$stream,
&$archiveTo
) {
if ($message->hasHeader(StreamStartHeader::class)) {
try {
$archiveTo = $message->header(PlayheadHeader::class)->playhead;
} catch (Throwable) {
}
}
return $message->withHeader(new StreamNameHeader($stream));
},
$messages,
)
);
if ($archiveTo === null) {
$this->store->save(...$messages);
return;
}
$this->store->transactional(
static function () use ($stream, $archiveTo, $messages): void {
$this->store->save(...$messages);
$this->store->archive(
new Criteria(
new StreamCriterion($stream),
new ToPlayheadCriterion($archiveTo),
),
);
}
);
}
}