|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* event-sourcing (https://github.com/phpgears/event-sourcing). |
|
5
|
|
|
* Event Sourcing base. |
|
6
|
|
|
* |
|
7
|
|
|
* @license MIT |
|
8
|
|
|
* @link https://github.com/phpgears/event-sourcing |
|
9
|
|
|
* @author Julián Gutiérrez <[email protected]> |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Gears\EventSourcing\Store\Snapshot; |
|
15
|
|
|
|
|
16
|
|
|
use Gears\EventSourcing\Aggregate\AggregateRoot; |
|
17
|
|
|
use Gears\EventSourcing\Aggregate\Serializer\AggregateSerializer; |
|
18
|
|
|
use Gears\EventSourcing\Store\Snapshot\Exception\SnapshotStoreException; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Abstract snapshot implementation. |
|
22
|
|
|
*/ |
|
23
|
|
|
abstract class AbstractSnapshotStore implements SnapshotStore |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* @var AggregateSerializer |
|
27
|
|
|
*/ |
|
28
|
|
|
private $serializer; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* AbstractSnapshotStore constructor. |
|
32
|
|
|
* |
|
33
|
|
|
* @param AggregateSerializer $serializer |
|
34
|
|
|
*/ |
|
35
|
|
|
public function __construct(AggregateSerializer $serializer) |
|
36
|
|
|
{ |
|
37
|
|
|
$this->serializer = $serializer; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Deserialize aggregate root. |
|
42
|
|
|
* |
|
43
|
|
|
* @param string $serializedAggregate |
|
44
|
|
|
* |
|
45
|
|
|
* @throws SnapshotStoreException |
|
46
|
|
|
* |
|
47
|
|
|
* @return AggregateRoot |
|
48
|
|
|
*/ |
|
49
|
|
|
final protected function deserializeAggregateRoot(string $serializedAggregate): AggregateRoot |
|
50
|
|
|
{ |
|
51
|
|
|
$aggregateRoot = $this->serializer->fromSerialized($serializedAggregate); |
|
52
|
|
|
|
|
53
|
|
|
if ($aggregateRoot->getRecordedAggregateEvents()->count() !== 0 |
|
54
|
|
|
|| $aggregateRoot->getRecordedEvents()->count() !== 0 |
|
55
|
|
|
) { |
|
56
|
|
|
throw new SnapshotStoreException('Aggregate root coming from snapshot cannot have recorded events'); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
return $aggregateRoot; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Serialize aggregate root. |
|
64
|
|
|
* |
|
65
|
|
|
* @param AggregateRoot $aggregateRoot |
|
66
|
|
|
* |
|
67
|
|
|
* @throws SnapshotStoreException |
|
68
|
|
|
* |
|
69
|
|
|
* @return string |
|
70
|
|
|
*/ |
|
71
|
|
|
final protected function serializeAggregateRoot(AggregateRoot $aggregateRoot): string |
|
72
|
|
|
{ |
|
73
|
|
|
if ($aggregateRoot->getRecordedAggregateEvents()->count() !== 0 |
|
74
|
|
|
|| $aggregateRoot->getRecordedEvents()->count() !== 0 |
|
75
|
|
|
) { |
|
76
|
|
|
throw new SnapshotStoreException('Aggregate root cannot have recorded events in order to be snapshoted'); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
return $this->serializer->serialize($aggregateRoot); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|