Passed
Pull Request — master (#84)
by Frank
14:06 queued 04:07
created

AggregateRootWithAggregates   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 21
c 1
b 0
f 1
dl 0
loc 57
rs 10
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 12 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
    protected function eventRecorder(): EventRecorder
16
    {
17
        static $eventRecorder;
18
19
        if ($eventRecorder === null) {
20
21
            $eventRecorder = new EventRecorder(function(object $event) {
22
                $this->recordThat($event);
23
            });
24
        }
25
26
        return $eventRecorder;
27
    }
28
29
    /**
30
     * @var SplObjectStorage|null
31
     */
32
    private $aggregatesInsideRoot;
33
34
    private function aggregatesInsideRoot(): SplObjectStorage
35
    {
36
        if ($this->aggregatesInsideRoot instanceof SplObjectStorage) {
37
            return $this->aggregatesInsideRoot;
38
        }
39
40
        return $this->aggregatesInsideRoot = new SplObjectStorage();
41
    }
42
43
    private function registerAggregate(?EventSourcedAggregate $aggregate): void
44
    {
45
        if ($aggregate instanceof EventSourcedAggregate) {
46
            $storage = $this->aggregatesInsideRoot();
47
            $storage->attach($aggregate);
48
        }
49
    }
50
51
    private function unregisterAggregate(?EventSourcedAggregate $aggregate): void
52
    {
53
        if ($aggregate instanceof EventSourcedAggregate) {
54
            $storage = $this->aggregatesInsideRoot();
55
            $storage->detach($aggregate);
56
        }
57
    }
58
59
    protected function apply(object $event): void
60
    {
61
        $this->applyOnAggregateRoot($event);
62
63
        /** @var EventSourcedAggregate $aggregate */
64
        foreach ($this->aggregatesInsideRoot() as $aggregate) {
65
            $aggregate->apply($event);
66
        }
67
    }
68
}
69