AggregateRoot   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 95
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 6
dl 0
loc 95
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A retrieve() 0 8 1
A recordThat() 0 8 1
A persist() 0 14 1
A getStoredEventRepository() 0 4 1
A getRecordedEvents() 0 4 1
A getAndClearRecordedEvents() 0 8 1
A reconstituteFromEvents() 0 9 1
A apply() 0 12 2
A fake() 0 6 1
1
<?php
2
3
namespace Spatie\EventProjector;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Support\Str;
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
        $storedEvents = call_user_func(
37
            [$this->getStoredEventRepository(), 'persistMany'],
38
            $this->getAndClearRecordedEvents(),
39
            $this->aggregateUuid
40
        );
41
42
        $storedEvents->each(function (StoredEvent $storedEvent) {
43
            $storedEvent->handle();
44
        });
45
46
        return $this;
47
    }
48
49
    protected function getStoredEventRepository(): StoredEventRepository
50
    {
51
        return app($this->storedEventRepository ?? config('event-projector.stored_event_repository'));
0 ignored issues
show
Bug introduced by
The property storedEventRepository does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
52
    }
53
54
    public function getRecordedEvents(): array
55
    {
56
        return $this->recordedEvents;
57
    }
58
59
    private function getAndClearRecordedEvents(): array
60
    {
61
        $recordedEvents = $this->recordedEvents;
62
63
        $this->recordedEvents = [];
64
65
        return $recordedEvents;
66
    }
67
68
    private function reconstituteFromEvents(): AggregateRoot
69
    {
70
        $this->getStoredEventRepository()->retrieveAll($this->aggregateUuid)
71
            ->each(function (StoredEvent $storedEvent) {
72
                $this->apply($storedEvent->event);
0 ignored issues
show
Bug introduced by
It seems like $storedEvent->event can be null; however, apply() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
73
            });
74
75
        return $this;
76
    }
77
78
    private function apply(ShouldBeStored $event): void
79
    {
80
        $classBaseName = class_basename($event);
81
82
        $camelCasedBaseName = ucfirst(Str::camel($classBaseName));
83
84
        $applyingMethodName = "apply{$camelCasedBaseName}";
85
86
        if (method_exists($this, $applyingMethodName)) {
87
            $this->$applyingMethodName($event);
88
        }
89
    }
90
91
    /**
92
     * @param \Spatie\EventProjector\ShouldBeStored|\Spatie\EventProjector\ShouldBeStored[] $events
93
     *
94
     * @return $this
95
     */
96
    public static function fake($events = []): FakeAggregateRoot
97
    {
98
        $events = Arr::wrap($events);
99
100
        return (new FakeAggregateRoot(app(static::class)))->given($events);
101
    }
102
}
103