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

BaseAggregateRoot::releaseEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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