Completed
Pull Request — master (#49)
by Frank
02:15
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 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing;
6
7
use Generator;
8
9
trait AggregateRootBehaviour
10
{
11
    /**
12
     * @var AggregateRootId
13
     */
14
    private $aggregateRootId;
15
16
    /**
17
     * @var int
18
     */
19
    private $aggregateRootVersion = 0;
20
21
    /**
22
     * @var object[]
23
     */
24
    private $recordedEvents = [];
25
26 8
    public function __construct(AggregateRootId $aggregateRootId)
27
    {
28 8
        $this->aggregateRootId = $aggregateRootId;
29 8
    }
30
31 8
    public function aggregateRootId(): AggregateRootId
32
    {
33 8
        return $this->aggregateRootId;
34
    }
35
36 8
    public function aggregateRootVersion(): int
37
    {
38 8
        return $this->aggregateRootVersion;
39
    }
40
41
    /**
42
     * @param AggregateRootId $aggregateRootId
43
     * @param Generator       $events
44
     *
45
     * @return static
46
     * @see AggregateRoot::reconstituteFromEvents
47
     */
48 8
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
49
    {
50 8
        $aggregateRoot = new static($aggregateRootId);
51
52
        /** @var object $event */
53 8
        foreach ($events as $event) {
54 2
            $aggregateRoot->apply($event);
55
        }
56
57 8
        return $aggregateRoot;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $aggregateRoot returns the type EventSauce\EventSourcing\AggregateRootBehaviour which is incompatible with the type-hinted return EventSauce\EventSourcing\AggregateRoot.
Loading history...
58
    }
59
60 4
    protected function apply(object $event)
61
    {
62 4
        $parts = explode('\\', get_class($event));
63 4
        $this->{'apply' . end($parts)}($event);
64 4
        $this->aggregateRootVersion++;
65 4
    }
66
67 4
    protected function recordThat(object $event)
68
    {
69 4
        $this->apply($event);
70 4
        $this->recordedEvents[] = $event;
71 4
    }
72
73
    /**
74
     * @return object[]
75
     */
76 8
    public function releaseEvents(): array
77
    {
78 8
        $releasedEvents = $this->recordedEvents;
79 8
        $this->recordedEvents = [];
80
81 8
        return $releasedEvents;
82
    }
83
}
84