1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EventSauce\EventSourcing; |
6
|
|
|
|
7
|
|
|
use SplObjectStorage; |
8
|
|
|
|
9
|
|
|
trait AggregateRootWithAggregates |
10
|
|
|
{ |
11
|
|
|
use AggregateRootBehaviour, AggregateAppliesKnownEvents { |
12
|
|
|
AggregateAppliesKnownEvents::apply as applyOnAggregateRoot; |
13
|
|
|
} |
14
|
|
|
|
15
|
1 |
|
protected function eventRecorder(): EventRecorder |
16
|
|
|
{ |
17
|
1 |
|
static $eventRecorder; |
18
|
|
|
|
19
|
1 |
|
if ($eventRecorder === null) { |
20
|
|
|
|
21
|
1 |
|
$eventRecorder = new EventRecorder(function(object $event) { |
22
|
1 |
|
$this->recordThat($event); |
23
|
1 |
|
}); |
24
|
|
|
} |
25
|
|
|
|
26
|
1 |
|
return $eventRecorder; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var SplObjectStorage|null |
31
|
|
|
*/ |
32
|
|
|
private $aggregatesInsideRoot; |
33
|
|
|
|
34
|
1 |
|
private function aggregatesInsideRoot(): SplObjectStorage |
35
|
|
|
{ |
36
|
1 |
|
if ($this->aggregatesInsideRoot instanceof SplObjectStorage) { |
37
|
1 |
|
return $this->aggregatesInsideRoot; |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
return $this->aggregatesInsideRoot = new SplObjectStorage(); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
private function registerAggregate(?EventSourcedAggregate $aggregate): void |
44
|
|
|
{ |
45
|
1 |
|
if ($aggregate instanceof EventSourcedAggregate) { |
46
|
1 |
|
$storage = $this->aggregatesInsideRoot(); |
47
|
1 |
|
$storage->attach($aggregate); |
48
|
|
|
} |
49
|
1 |
|
} |
50
|
|
|
|
51
|
1 |
|
private function unregisterAggregate(?EventSourcedAggregate $aggregate): void |
52
|
|
|
{ |
53
|
1 |
|
if ($aggregate instanceof EventSourcedAggregate) { |
54
|
1 |
|
$storage = $this->aggregatesInsideRoot(); |
55
|
1 |
|
$storage->detach($aggregate); |
56
|
|
|
} |
57
|
1 |
|
} |
58
|
|
|
|
59
|
1 |
|
protected function apply(object $event): void |
60
|
|
|
{ |
61
|
1 |
|
$this->applyOnAggregateRoot($event); |
62
|
|
|
|
63
|
|
|
/** @var EventSourcedAggregate $aggregate */ |
64
|
1 |
|
foreach ($this->aggregatesInsideRoot() as $aggregate) { |
65
|
1 |
|
$aggregate->apply($event); |
66
|
|
|
} |
67
|
1 |
|
} |
68
|
|
|
} |
69
|
|
|
|