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

aggregatesInsideRoot()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
c 1
b 0
f 1
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
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