Passed
Pull Request — master (#84)
by Frank
10:46 queued 47s
created

AggregateRootWithAggregates   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 20
dl 0
loc 54
rs 10
c 2
b 0
f 1
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A unregisterAggregate() 0 5 2
A registerAggregate() 0 5 2
A apply() 0 7 2
A eventRecorder() 0 9 2
A aggregatesInsideRoot() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing;
6
7
use SplObjectStorage;
8
9
trait AggregateRootWithAggregates
10
{
11
    use AggregateRootBehaviour, AggregateAppliesKnownEvents {
12
        AggregateAppliesKnownEvents::apply as applyOnAggregateRoot;
13
    }
14
15
    /**
16
     * @var SplObjectStorage|null
17
     */
18
    private $aggregatesInsideRoot = null;
19
20
    protected function eventRecorder(): EventRecorder
21
    {
22
        static $eventRecorder;
23
24
        if (null === $eventRecorder) {
25
            $eventRecorder = new EventRecorder(fn (object $event) => $this->recordThat($event));
26
        }
27
28
        return $eventRecorder;
29
    }
30
31
    private function aggregatesInsideRoot(): SplObjectStorage
32
    {
33
        if ($this->aggregatesInsideRoot instanceof SplObjectStorage) {
34
            return $this->aggregatesInsideRoot;
35
        }
36
37
        return $this->aggregatesInsideRoot = new SplObjectStorage();
38
    }
39
40
    private function registerAggregate(?EventSourcedAggregate $aggregate): void
41
    {
42
        if ($aggregate instanceof EventSourcedAggregate) {
43
            $storage = $this->aggregatesInsideRoot();
44
            $storage->attach($aggregate);
45
        }
46
    }
47
48
    private function unregisterAggregate(?EventSourcedAggregate $aggregate): void
49
    {
50
        if ($aggregate instanceof EventSourcedAggregate) {
51
            $storage = $this->aggregatesInsideRoot();
52
            $storage->detach($aggregate);
53
        }
54
    }
55
56
    protected function apply(object $event): void
57
    {
58
        $this->applyOnAggregateRoot($event);
59
60
        /** @var EventSourcedAggregate $aggregate */
61
        foreach ($this->aggregatesInsideRoot() as $aggregate) {
62
            $aggregate->apply($event);
63
        }
64
    }
65
}
66