AggregateRoot::apply()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 6
cp 0
crap 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\EventSource\Domain\Model\Aggregate;
6
7
use Antidot\EventSource\Domain\Event\AggregateChanged;
8
use Antidot\EventSource\Domain\Event\DomainEventEmitter;
9
use Antidot\EventSource\Domain\Event\EventCollection;
10
11
abstract class AggregateRoot
12
{
13
    public const EVENT_MAP = [];
14
    protected array $events;
15
    protected string $aggregateId;
16
17
    final public function __construct()
18
    {
19
        $this->events = [];
20
    }
21
22
    public function aggregateId(): string
23
    {
24
        return $this->aggregateId;
25
    }
26
27
    protected function recordThat(AggregateChanged $occur): void
28
    {
29
        $this->events[] = $occur;
30
        DomainEventEmitter::recordThat($occur);
31
    }
32
33
    public function popEvents(): EventCollection
34
    {
35
        $appliedEvents = [];
36
        /**
37
         * @var int $key
38
         * @var AggregateChanged $event
39
         */
40
        foreach ($this->events as $key => $event) {
41
            $this->apply($event);
42
            unset($this->events[$key]);
43
            $appliedEvents[] = $event;
44
        }
45
46
        return EventCollection::createImmutableCollection($appliedEvents);
47
    }
48
49
    public function apply(AggregateChanged $aggregateChanged): void
50
    {
51
        /** @var array<string, string>  */
52
        $eventMap = static::EVENT_MAP;
53
        $eventClass = get_class($aggregateChanged);
54
        if (array_key_exists($eventClass, $eventMap)) {
55
            $method = $eventMap[$eventClass];
56
            $this->{$method}($aggregateChanged);
57
        }
58
    }
59
}
60