Passed
Pull Request — master (#84)
by Frank
03:17
created

AggregateRootBehaviour   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
eloc 19
c 6
b 0
f 0
dl 0
loc 73
ccs 21
cts 21
cp 1
rs 10
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A releaseEvents() 0 6 1
A recordThat() 0 4 1
A aggregateRootId() 0 3 1
A reconstituteFromEvents() 0 14 3
A aggregateRootVersion() 0 3 1
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing;
6
7
use Generator;
8
9
/**
10
 * @see AggregateRoot
11
 */
12
trait AggregateRootBehaviour
13
{
14
    use AggregateAlwaysAppliesEvents {
15
        apply as protected;
16
    }
17
18
    /**
19
     * @var AggregateRootId
20
     */
21
    private $aggregateRootId;
22
23
    /**
24
     * @var int
25
     */
26
    private $aggregateRootVersion = 0;
27
28
    /**
29
     * @var object[]
30
     */
31
    private $recordedEvents = [];
32
33 18
    private function __construct(AggregateRootId $aggregateRootId)
34
    {
35 18
        $this->aggregateRootId = $aggregateRootId;
36 18
    }
37
38 15
    public function aggregateRootId(): AggregateRootId
39
    {
40 15
        return $this->aggregateRootId;
41
    }
42
43
    /**
44
     * @see AggregateRoot::aggregateRootVersion
45
     */
46 17
    public function aggregateRootVersion(): int
47
    {
48 17
        return $this->aggregateRootVersion;
49
    }
50
51 10
    protected function recordThat(object $event): void
52
    {
53 10
        $this->apply($event);
54 10
        $this->recordedEvents[] = $event;
55 10
    }
56
57
    /**
58
     * @return object[]
59
     */
60 15
    public function releaseEvents(): array
61
    {
62 15
        $releasedEvents = $this->recordedEvents;
63 15
        $this->recordedEvents = [];
64
65 15
        return $releasedEvents;
66
    }
67
68
    /**
69
     * @see AggregateRoot::reconstituteFromEvents
70
     */
71 16
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
72
    {
73
        /** @var AggregateRoot&static $aggregateRoot */
74 16
        $aggregateRoot = new static($aggregateRootId);
75
76
        /** @var object $event */
77 16
        foreach ($events as $event) {
78 7
            $aggregateRoot->apply($event);
79
        }
80
81 16
        $aggregateRoot->aggregateRootVersion = $events->getReturn() ?: 0;
82
83
        /* @var AggregateRoot $aggregateRoot */
84 16
        return $aggregateRoot;
85
    }
86
}
87