1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace EventSauce\EventSourcing; |
||
6 | |||
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 | 8 | public function __construct(AggregateRootId $aggregateRootId) |
|
27 | { |
||
28 | 8 | $this->aggregateRootId = $aggregateRootId; |
|
29 | 8 | } |
|
30 | |||
31 | 8 | public function aggregateRootId(): AggregateRootId |
|
32 | { |
||
33 | 8 | return $this->aggregateRootId; |
|
34 | } |
||
35 | |||
36 | 8 | public function aggregateRootVersion(): int |
|
37 | { |
||
38 | 8 | return $this->aggregateRootVersion; |
|
39 | } |
||
40 | |||
41 | 4 | protected function apply(object $event) |
|
42 | { |
||
43 | 4 | $parts = explode('\\', get_class($event)); |
|
44 | 4 | $this->{'apply' . end($parts)}($event); |
|
45 | 4 | $this->aggregateRootVersion++; |
|
46 | 4 | } |
|
47 | |||
48 | 4 | protected function recordThat(object $event) |
|
49 | { |
||
50 | 4 | $this->apply($event); |
|
51 | 4 | $this->recordedEvents[] = $event; |
|
52 | 4 | } |
|
53 | |||
54 | /** |
||
55 | * @return object[] |
||
56 | */ |
||
57 | 8 | public function releaseEvents(): array |
|
58 | { |
||
59 | 8 | $releasedEvents = $this->recordedEvents; |
|
60 | 8 | $this->recordedEvents = []; |
|
61 | |||
62 | 8 | return $releasedEvents; |
|
63 | } |
||
64 | |||
65 | /** |
||
66 | * @param AggregateRootId $aggregateRootId |
||
67 | * @param Generator $events |
||
68 | * |
||
69 | * @return static |
||
70 | * @see AggregateRoot::reconstituteFromEvents |
||
71 | */ |
||
72 | 8 | public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot |
|
73 | { |
||
74 | /** @var AggregateRoot|static $aggregateRoot */ |
||
75 | 8 | $aggregateRoot = new static($aggregateRootId); |
|
76 | |||
77 | /** @var object $event */ |
||
78 | 8 | foreach ($events as $event) { |
|
79 | 2 | $aggregateRoot->apply($event); |
|
80 | } |
||
81 | |||
82 | 8 | return $aggregateRoot; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
83 | } |
||
84 | } |
||
85 |