Passed
Pull Request — master (#84)
by Frank
10:15 queued 08:09
created

AggregateRootWithAggregates   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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