Completed
Push — master ( e5ea90...aeffd7 )
by Freek
09:52 queued 08:11
created

AggregateRoot::getAndClearRecoredEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\EventProjector;
4
5
use Illuminate\Support\Str;
6
use Spatie\EventProjector\Models\StoredEvent;
7
8
abstract class AggregateRoot
9
{
10
    /** @var string */
11
    private $aggregateUuid;
12
13
    /** @var array */
14
    private $recordedEvents = [];
15
16
    public static function retrieve(string $uuid): AggregateRoot
17
    {
18
        $aggregateRoot = (new static());
19
20
        $aggregateRoot->aggregateUuid = $uuid;
21
22
        return $aggregateRoot->reconstituteFromEvents();
23
    }
24
25
    public function recordThat(ShouldBeStored $domainEvent): AggregateRoot
26
    {
27
        $this->recordedEvents[] = $domainEvent;
28
29
        $this->apply($domainEvent);
30
31
        return $this;
32
    }
33
34
    public function persist(): AggregateRoot
35
    {
36
        call_user_func(
37
            [config('event-projector.stored_event_model'), 'storeMany'],
38
            $this->getAndClearRecoredEvents(),
39
            $this->aggregateUuid
40
        );
41
42
        return $this;
43
    }
44
45
    private function getAndClearRecoredEvents(): array
46
    {
47
        $recordedEvents = $this->recordedEvents;
48
49
        $this->recordedEvents = [];
50
51
        return $recordedEvents;
52
    }
53
54
    private function reconstituteFromEvents(): AggregateRoot
55
    {
56
        StoredEvent::uuid($this->aggregateUuid)->each(function (StoredEvent $storedEvent) {
57
            $this->apply($storedEvent->event);
58
        });
59
60
        return $this;
61
    }
62
63
    private function apply(ShouldBeStored $event): void
64
    {
65
        $classBaseName = class_basename($event);
66
67
        $camelCasedBaseName = ucfirst(Str::camel($classBaseName));
68
69
        $applyingMethodName = "apply{$camelCasedBaseName}";
70
71
        if (method_exists($this, $applyingMethodName)) {
72
            $this->$applyingMethodName($event);
73
        }
74
    }
75
}
76