Passed
Push — master ( 97a5b7...e77720 )
by Frank
46s queued 10s
created

AggregateRootBehaviour::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
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 4
    protected function apply(object $event)
42
    {
43 4
        $parts = explode('\\', get_class($event));
44 4
        $this->{'apply' . end($parts)}($event);
45 4
        $this->aggregateRootVersion++;
46 4
    }
47
48 4
    protected function recordThat(object $event)
49
    {
50 4
        $this->apply($event);
51 4
        $this->recordedEvents[] = $event;
52 4
    }
53
54
    /**
55
     * @return object[]
56
     */
57 8
    public function releaseEvents(): array
58
    {
59 8
        $releasedEvents = $this->recordedEvents;
60 8
        $this->recordedEvents = [];
61
62 8
        return $releasedEvents;
63
    }
64
65
    /**
66
     * @param AggregateRootId $aggregateRootId
67
     * @param Generator       $events
68
     *
69
     * @return static
70
     * @see AggregateRoot::reconstituteFromEvents
71
     */
72 8
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
73
    {
74
        /** @var AggregateRoot|static $aggregateRoot */
75 8
        $aggregateRoot = new static($aggregateRootId);
76
77
        /** @var object $event */
78 8
        foreach ($events as $event) {
79 2
            $aggregateRoot->apply($event);
80
        }
81
82 8
        return $aggregateRoot;
0 ignored issues
show
Bug Best Practice introduced by Frank de Jonge
The expression return $aggregateRoot returns the type EventSauce\EventSourcing\AggregateRootBehaviour which is incompatible with the type-hinted return EventSauce\EventSourcing\AggregateRoot.
Loading history...
83
    }
84
}
85