Completed
Push — master ( 25f418...613f8b )
by Frank
01:39
created

BaseAggregateRoot   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 64
c 0
b 0
f 0
wmc 7
lcom 1
cbo 0
ccs 23
cts 23
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A aggregateRootId() 0 4 1
A recordThat() 0 5 1
A releaseEvents() 0 7 1
A apply() 0 5 1
A reconstituteFromEvents() 0 11 2
1
<?php
2
3
namespace EventSauce\EventSourcing;
4
5
use Generator;
6
use function explode;
7
use function get_class;
8
9
abstract class BaseAggregateRoot implements AggregateRoot
10
{
11
    /**
12
     * @var Event[]
13
     */
14
    private $recordedEvents;
15
16
    /**
17
     * @var AggregateRootId
18
     */
19
    private $aggregateRootId;
20
21 6
    final public function __construct(AggregateRootId $aggregateRootId)
22
    {
23 6
        $this->recordedEvents = [];
24 6
        $this->aggregateRootId = $aggregateRootId;
25 6
    }
26
27 2
    public function aggregateRootId(): AggregateRootId
28
    {
29 2
        return $this->aggregateRootId;
30
    }
31
32 2
    protected function recordThat(Event $event)
33
    {
34 2
        $this->apply($event);
35 2
        $this->recordedEvents[] = $event;
36 2
    }
37
38
    /**
39
     * @return Event[]
40
     */
41 6
    public function releaseEvents(): array
42
    {
43 6
        $releasedEvents = $this->recordedEvents;
44 6
        $this->recordedEvents = [];
45
46 6
        return $releasedEvents;
47
    }
48
49 2
    protected function apply(Event $event)
50
    {
51 2
        $parts = explode('\\', get_class($event));
52 2
        $this->{'apply' . end($parts)}($event);
53 2
    }
54
55
    /**
56
     * @param AggregateRootId $aggregateRootId
57
     * @param Generator           $events
58
     *
59
     * @return static
60
     */
61 6
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
62
    {
63 6
        $aggregateRoot = new static($aggregateRootId);
64
65
        /** @var Event $event */
66 6
        foreach ($events as $event) {
67 1
            $aggregateRoot->apply($event);
68
        }
69
70 6
        return $aggregateRoot;
71
    }
72
}