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
|
|
|
/** |
16
|
|
|
* @var SplObjectStorage|null |
17
|
|
|
*/ |
18
|
|
|
private $aggregatesInsideRoot = null; |
19
|
|
|
|
20
|
|
|
protected function eventRecorder(): EventRecorder |
21
|
|
|
{ |
22
|
|
|
static $eventRecorder; |
23
|
|
|
|
24
|
|
|
if (null === $eventRecorder) { |
25
|
|
|
$eventRecorder = new EventRecorder(fn (object $event) => $this->recordThat($event)); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
return $eventRecorder; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
private function aggregatesInsideRoot(): SplObjectStorage |
32
|
|
|
{ |
33
|
|
|
if ($this->aggregatesInsideRoot instanceof SplObjectStorage) { |
34
|
|
|
return $this->aggregatesInsideRoot; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $this->aggregatesInsideRoot = new SplObjectStorage(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
private function registerAggregate(?EventSourcedAggregate $aggregate): void |
41
|
|
|
{ |
42
|
|
|
if ($aggregate instanceof EventSourcedAggregate) { |
43
|
|
|
$storage = $this->aggregatesInsideRoot(); |
44
|
|
|
$storage->attach($aggregate); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function unregisterAggregate(?EventSourcedAggregate $aggregate): void |
49
|
|
|
{ |
50
|
|
|
if ($aggregate instanceof EventSourcedAggregate) { |
51
|
|
|
$storage = $this->aggregatesInsideRoot(); |
52
|
|
|
$storage->detach($aggregate); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
protected function apply(object $event): void |
57
|
|
|
{ |
58
|
|
|
$this->applyOnAggregateRoot($event); |
59
|
|
|
|
60
|
|
|
/** @var EventSourcedAggregate $aggregate */ |
61
|
|
|
foreach ($this->aggregatesInsideRoot() as $aggregate) { |
62
|
|
|
$aggregate->apply($event); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|