This repository has been archived by the owner on Sep 20, 2019. It is now read-only.
/
AggregateRoot.php
98 lines (73 loc) 路 2.31 KB
/
AggregateRoot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Spatie\EventProjector;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Spatie\EventProjector\Models\StoredEvent;
abstract class AggregateRoot
{
/** @var string */
private $aggregateUuid;
/** @var array */
private $recordedEvents = [];
public static function retrieve(string $uuid): AggregateRoot
{
$aggregateRoot = (new static());
$aggregateRoot->aggregateUuid = $uuid;
return $aggregateRoot->reconstituteFromEvents();
}
public function recordThat(ShouldBeStored $domainEvent): AggregateRoot
{
$this->recordedEvents[] = $domainEvent;
$this->apply($domainEvent);
return $this;
}
public function persist(): AggregateRoot
{
call_user_func(
[$this->getStoredEventModel(), 'storeMany'],
$this->getAndClearRecordedEvents(),
$this->aggregateUuid
);
return $this;
}
protected function getStoredEventModel(): string
{
return $this->storedEventModel ?? config('event-projector.stored_event_model');
}
public function getRecordedEvents(): array
{
return $this->recordedEvents;
}
private function getAndClearRecordedEvents(): array
{
$recordedEvents = $this->recordedEvents;
$this->recordedEvents = [];
return $recordedEvents;
}
private function reconstituteFromEvents(): AggregateRoot
{
$this->getStoredEventModel()::uuid($this->aggregateUuid)->each(function (StoredEvent $storedEvent) {
$this->apply($storedEvent->event);
});
return $this;
}
private function apply(ShouldBeStored $event): void
{
$classBaseName = class_basename($event);
$camelCasedBaseName = ucfirst(Str::camel($classBaseName));
$applyingMethodName = "apply{$camelCasedBaseName}";
if (method_exists($this, $applyingMethodName)) {
$this->$applyingMethodName($event);
}
}
/**
* @param \Spatie\EventProjector\ShouldBeStored|\Spatie\EventProjector\ShouldBeStored[] $events
*
* @return $this
*/
public static function fake($events = []): FakeAggregateRoot
{
$events = Arr::wrap($events);
return (new FakeAggregateRoot(app(static::class)))->given($events);
}
}