1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Blixit\EventSourcing\Store\InMemory; |
6
|
|
|
|
7
|
|
|
use Blixit\EventSourcing\Event\EventInterface; |
8
|
|
|
use Blixit\EventSourcing\Store\Matcher\EventMatcherInterface; |
9
|
|
|
use Blixit\EventSourcing\Store\Persistence\EventPersisterInterface; |
10
|
|
|
use Blixit\EventSourcing\Stream\StreamName; |
11
|
|
|
use function array_filter; |
12
|
|
|
|
13
|
|
|
class InMemoryEventPersister implements EventPersisterInterface |
14
|
|
|
{ |
15
|
|
|
/** @var EventInterface[] $events */ |
16
|
|
|
private $events = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @return EventInterface[] |
20
|
|
|
*/ |
21
|
|
|
public function getByStream(StreamName $streamName, ?int $fromSequence = 0) : array |
22
|
|
|
{ |
23
|
|
|
return array_filter($this->events, static function (EventInterface $event) use ( |
24
|
|
|
$streamName, |
25
|
|
|
$fromSequence |
26
|
|
|
) { |
27
|
|
|
return $event->getStreamName() === (string) $streamName && $event->getSequence() > $fromSequence; |
28
|
|
|
}); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function persist(EventInterface $event) : EventInterface |
32
|
|
|
{ |
33
|
|
|
$this->events[] = $event; |
34
|
|
|
|
35
|
|
|
return $event; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @return EventInterface[] |
40
|
|
|
*/ |
41
|
|
|
public function find(EventMatcherInterface $eventMatcher) : array |
42
|
|
|
{ |
43
|
|
|
$aggregateId = $eventMatcher->getAggregateId(); |
44
|
|
|
$aggregateClass = $eventMatcher->getAggregateClass(); |
45
|
|
|
$fromSequence = $eventMatcher->getSequence(); |
46
|
|
|
$streamName = $eventMatcher->getStreamName(); |
47
|
|
|
$timestamp = $eventMatcher->getTimestamp(); |
48
|
|
|
|
49
|
|
|
return array_filter($this->events, static function (EventInterface $event) use ( |
50
|
|
|
$aggregateId, |
51
|
|
|
$aggregateClass, |
52
|
|
|
$fromSequence, |
53
|
|
|
$streamName, |
54
|
|
|
$timestamp |
55
|
|
|
) { |
56
|
|
|
$condition = true; |
57
|
|
|
if (! empty($aggregateId)) { |
58
|
|
|
$condition = $condition && ($event->getAggregateId() === (string) $aggregateId); |
59
|
|
|
} |
60
|
|
|
if (! empty($aggregateClass)) { |
61
|
|
|
$condition = $condition && ($event->getAggregateClass() === (string) $aggregateClass); |
62
|
|
|
} |
63
|
|
|
if (! empty($fromSequence)) { |
64
|
|
|
$condition = $condition && ($event->getSequence() > $fromSequence); |
65
|
|
|
} |
66
|
|
|
if (! empty($streamName)) { |
67
|
|
|
$condition = $condition && ($event->getStreamName() === (string) $streamName); |
68
|
|
|
} |
69
|
|
|
if (! empty($timestamp)) { |
70
|
|
|
$condition = $condition && ($event->getStreamName() > $timestamp); |
71
|
|
|
} |
72
|
|
|
return $condition; |
73
|
|
|
}); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|