Passed
Pull Request — master (#84)
by Frank
15:42 queued 05:42
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
    /**
19
     * @var AggregateRootId
20
     */
21
    private $aggregateRootId;
22
23
    /**
24
     * @var int
25
     */
26
    private $aggregateRootVersion = 0;
27
28
    /**
29 17
     * @var object[]
30
     */
31 17
    private $recordedEvents = [];
32 17
33
    private function __construct(AggregateRootId $aggregateRootId)
34 14
    {
35
        $this->aggregateRootId = $aggregateRootId;
36 14
    }
37
38
    public function aggregateRootId(): AggregateRootId
39
    {
40
        return $this->aggregateRootId;
41
    }
42 16
43
    /**
44 16
     * @see AggregateRoot::aggregateRootVersion
45
     */
46
    public function aggregateRootVersion(): int
47 11
    {
48
        return $this->aggregateRootVersion;
49 11
    }
50 11
51 11
    protected function recordThat(object $event): void
52 11
    {
53
        $this->apply($event);
54 9
        $this->recordedEvents[] = $event;
55
    }
56 9
57 9
    /**
58 9
     * @return object[]
59
     */
60
    public function releaseEvents(): array
61
    {
62
        $releasedEvents = $this->recordedEvents;
63 14
        $this->recordedEvents = [];
64
65 14
        return $releasedEvents;
66 14
    }
67
68 14
    /**
69
     * @see AggregateRoot::reconstituteFromEvents
70
     */
71
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
72
    {
73
        /** @var AggregateRoot&static $aggregateRoot */
74 15
        $aggregateRoot = new static($aggregateRootId);
75
76
        /** @var object $event */
77 15
        foreach ($events as $event) {
78
            $aggregateRoot->apply($event);
79
        }
80 15
81 6
        $aggregateRoot->aggregateRootVersion = $events->getReturn() ?: 0;
82
83
        /* @var AggregateRoot $aggregateRoot */
84 15
        return $aggregateRoot;
85
    }
86
}
87