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

AggregateRootBehaviour::apply()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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