1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace DDDominio\EventSourcing\Snapshotting; |
4
|
|
|
|
5
|
|
|
class InMemorySnapshotStore implements SnapshotStoreInterface |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* @var SnapshotInterface[] |
9
|
|
|
*/ |
10
|
|
|
private $snapshots; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @param SnapshotInterface[] $snapshots |
14
|
|
|
*/ |
15
|
15 |
|
public function __construct(array $snapshots = []) |
16
|
|
|
{ |
17
|
15 |
|
$this->snapshots = $snapshots; |
18
|
15 |
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param SnapshotInterface $snapshot |
22
|
|
|
*/ |
23
|
1 |
|
public function addSnapshot($snapshot) |
24
|
|
|
{ |
25
|
1 |
|
$this->snapshots[$snapshot->aggregateClass()][$snapshot->aggregateId()][] = $snapshot; |
26
|
1 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $aggregateClass |
30
|
|
|
* @param string $aggregateId |
31
|
|
|
* @return SnapshotInterface|null |
32
|
|
|
*/ |
33
|
3 |
|
public function findLastSnapshot($aggregateClass, $aggregateId) |
34
|
|
|
{ |
35
|
3 |
|
if (!isset($this->snapshots[$aggregateClass][$aggregateId])) { |
36
|
1 |
|
return null; |
37
|
|
|
} |
38
|
|
|
|
39
|
2 |
|
$snapshots = $this->snapshots[$aggregateClass][$aggregateId]; |
40
|
|
|
|
41
|
2 |
|
return end($snapshots); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $aggregateClass |
46
|
|
|
* @param string $aggregateId |
47
|
|
|
* @param int $version |
48
|
|
|
* @return SnapshotInterface|null |
49
|
|
|
*/ |
50
|
4 |
|
public function findNearestSnapshotToVersion($aggregateClass, $aggregateId, $version) |
51
|
|
|
{ |
52
|
4 |
|
if (!isset($this->snapshots[$aggregateClass][$aggregateId])) { |
53
|
2 |
|
return null; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** @var SnapshotInterface[] $snapshots */ |
57
|
2 |
|
$snapshots = $this->snapshots[$aggregateClass][$aggregateId]; |
58
|
|
|
|
59
|
2 |
|
$previousSnapshot = null; |
60
|
2 |
|
foreach ($snapshots as $snapshot) { |
61
|
2 |
|
if ($snapshot->version() < $version) { |
62
|
2 |
|
$previousSnapshot = $snapshot; |
63
|
|
|
} else { |
64
|
2 |
|
break; |
65
|
|
|
} |
66
|
|
|
} |
67
|
2 |
|
return $previousSnapshot; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|