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