Completed
Push — master ( c1932e...0de009 )
by Freek
27s queued 11s
created

AggregateRoot::getStoredEventRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
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\Arr;
6
use Illuminate\Support\Str;
7
use Spatie\EventProjector\Models\StoredEvent;
8
9
abstract class AggregateRoot
10
{
11
    /** @var string */
12
    private $aggregateUuid;
13
14
    /** @var array */
15
    private $recordedEvents = [];
16
17
    public static function retrieve(string $uuid): AggregateRoot
18
    {
19
        $aggregateRoot = (new static());
20
21
        $aggregateRoot->aggregateUuid = $uuid;
22
23
        return $aggregateRoot->reconstituteFromEvents();
24
    }
25
26
    public function recordThat(ShouldBeStored $domainEvent): AggregateRoot
27
    {
28
        $this->recordedEvents[] = $domainEvent;
29
30
        $this->apply($domainEvent);
31
32
        return $this;
33
    }
34
35
    public function persist(): AggregateRoot
36
    {
37
        $storedEvents = call_user_func(
38
            [$this->getStoredEventRepository(), 'persistMany'],
39
            $this->getAndClearRecordedEvents(),
40
            $this->aggregateUuid
41
        );
42
43
        $storedEvents->each(function (StoredEvent $storedEvent) {
44
            $storedEvent->handle();
45
        });
46
47
        return $this;
48
    }
49
50
    protected function getStoredEventRepository(): StoredEventRepository
51
    {
52
        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...
53
    }
54
55
    public function getRecordedEvents(): array
56
    {
57
        return $this->recordedEvents;
58
    }
59
60
    private function getAndClearRecordedEvents(): array
61
    {
62
        $recordedEvents = $this->recordedEvents;
63
64
        $this->recordedEvents = [];
65
66
        return $recordedEvents;
67
    }
68
69
    private function reconstituteFromEvents(): AggregateRoot
70
    {
71
        $this->getStoredEventRepository()->retrieveAll($this->aggregateUuid)
72
            ->each(function (StoredEvent $storedEvent) {
73
                $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...
74
            });
75
76
        return $this;
77
    }
78
79
    private function apply(ShouldBeStored $event): void
80
    {
81
        $classBaseName = class_basename($event);
82
83
        $camelCasedBaseName = ucfirst(Str::camel($classBaseName));
84
85
        $applyingMethodName = "apply{$camelCasedBaseName}";
86
87
        if (method_exists($this, $applyingMethodName)) {
88
            $this->$applyingMethodName($event);
89
        }
90
    }
91
92
    /**
93
     * @param \Spatie\EventProjector\ShouldBeStored|\Spatie\EventProjector\ShouldBeStored[] $events
94
     *
95
     * @return $this
96
     */
97
    public static function fake($events = []): FakeAggregateRoot
98
    {
99
        $events = Arr::wrap($events);
100
101
        return (new FakeAggregateRoot(app(static::class)))->given($events);
102
    }
103
}
104