Passed
Pull Request — master (#84)
by Frank
19:07 queued 09:07
created

AggregateRootBehaviour   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
A aggregateRootId() 0 3 1
A releaseEvents() 0 6 1
A reconstituteFromEvents() 0 12 3
A aggregateRootVersion() 0 3 1
A recordThat() 0 4 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
    private AggregateRootId $aggregateRootId;
19
    private int $aggregateRootVersion = 0;
20
    /** @var object[] */
21
    private array $recordedEvents = [];
22
23
    private function __construct(AggregateRootId $aggregateRootId)
24
    {
25
        $this->aggregateRootId = $aggregateRootId;
26
    }
27
28
    public function aggregateRootId(): AggregateRootId
29 17
    {
30
        return $this->aggregateRootId;
31 17
    }
32 17
33
    /**
34 14
     * @see AggregateRoot::aggregateRootVersion
35
     */
36 14
    public function aggregateRootVersion(): int
37
    {
38
        return $this->aggregateRootVersion;
39
    }
40
41
    protected function recordThat(object $event): void
42 16
    {
43
        $this->apply($event);
44 16
        $this->recordedEvents[] = $event;
45
    }
46
47 11
    /**
48
     * @return object[]
49 11
     */
50 11
    public function releaseEvents(): array
51 11
    {
52 11
        $releasedEvents = $this->recordedEvents;
53
        $this->recordedEvents = [];
54 9
55
        return $releasedEvents;
56 9
    }
57 9
58 9
    /**
59
     * @see AggregateRoot::reconstituteFromEvents
60
     */
61
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): static
62
    {
63 14
        $aggregateRoot = new static($aggregateRootId);
64
65 14
        /** @var object $event */
66 14
        foreach ($events as $event) {
67
            $aggregateRoot->apply($event);
68 14
        }
69
70
        $aggregateRoot->aggregateRootVersion = $events->getReturn() ?: 0;
71
72
        return $aggregateRoot;
73
    }
74
}
75