1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EventSauce\EventSourcing; |
6
|
|
|
|
7
|
|
|
use Generator; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @see AggregateRoot |
11
|
|
|
*/ |
12
|
|
|
trait AggregateRootBehaviour |
13
|
|
|
{ |
14
|
|
|
use AggregateAlwaysAppliesEvents { |
15
|
|
|
apply as protected; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var AggregateRootId |
20
|
|
|
*/ |
21
|
|
|
private $aggregateRootId; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var int |
25
|
|
|
*/ |
26
|
|
|
private $aggregateRootVersion = 0; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var object[] |
30
|
|
|
*/ |
31
|
|
|
private $recordedEvents = []; |
32
|
|
|
|
33
|
18 |
|
private function __construct(AggregateRootId $aggregateRootId) |
34
|
|
|
{ |
35
|
18 |
|
$this->aggregateRootId = $aggregateRootId; |
36
|
18 |
|
} |
37
|
|
|
|
38
|
15 |
|
public function aggregateRootId(): AggregateRootId |
39
|
|
|
{ |
40
|
15 |
|
return $this->aggregateRootId; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @see AggregateRoot::aggregateRootVersion |
45
|
|
|
*/ |
46
|
17 |
|
public function aggregateRootVersion(): int |
47
|
|
|
{ |
48
|
17 |
|
return $this->aggregateRootVersion; |
49
|
|
|
} |
50
|
|
|
|
51
|
10 |
|
protected function recordThat(object $event): void |
52
|
|
|
{ |
53
|
10 |
|
$this->apply($event); |
54
|
10 |
|
$this->recordedEvents[] = $event; |
55
|
10 |
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @return object[] |
59
|
|
|
*/ |
60
|
15 |
|
public function releaseEvents(): array |
61
|
|
|
{ |
62
|
15 |
|
$releasedEvents = $this->recordedEvents; |
63
|
15 |
|
$this->recordedEvents = []; |
64
|
|
|
|
65
|
15 |
|
return $releasedEvents; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @see AggregateRoot::reconstituteFromEvents |
70
|
|
|
*/ |
71
|
16 |
|
public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot |
72
|
|
|
{ |
73
|
|
|
/** @var AggregateRoot&static $aggregateRoot */ |
74
|
16 |
|
$aggregateRoot = new static($aggregateRootId); |
75
|
|
|
|
76
|
|
|
/** @var object $event */ |
77
|
16 |
|
foreach ($events as $event) { |
78
|
7 |
|
$aggregateRoot->apply($event); |
79
|
|
|
} |
80
|
|
|
|
81
|
16 |
|
$aggregateRoot->aggregateRootVersion = $events->getReturn() ?: 0; |
82
|
|
|
|
83
|
|
|
/* @var AggregateRoot $aggregateRoot */ |
84
|
16 |
|
return $aggregateRoot; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|