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

aggregatesInsideRoot()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

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
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
    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