Completed
Pull Request — master (#20)
by Frank
03:20
created

ConstructionBehaviour   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 46
c 0
b 0
f 0
wmc 5
lcom 1
cbo 0
ccs 13
cts 13
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A aggregateRootId() 0 4 1
A aggregateRootVersion() 0 4 1
A reconstituteFromEvents() 0 12 2
apply() 0 1 ?
1
<?php
2
3
namespace EventSauce\EventSourcing\AggregateRootBehaviour;
4
5
use EventSauce\EventSourcing\AggregateRoot;
6
use EventSauce\EventSourcing\AggregateRootId;
7
use EventSauce\EventSourcing\Event;
8
use Generator;
9
10
trait ConstructionBehaviour
11
{
12
13
    /**
14
     * @var AggregateRootId
15
     */
16
    private $aggregateRootId;
17
18
    private $aggregateRootVersion = 0;
19
20 8
    public function __construct(AggregateRootId $aggregateRootId)
21
    {
22 8
        $this->aggregateRootId = $aggregateRootId;
23 8
    }
24
25 8
    public function aggregateRootId(): AggregateRootId
26
    {
27 8
        return $this->aggregateRootId;
28
    }
29
30 8
    public function aggregateRootVersion(): int
31
    {
32 8
        return $this->aggregateRootVersion;
33
    }
34
35
    /**
36
     * @param AggregateRootId $aggregateRootId
37
     * @param Generator           $events
38
     *
39
     * @return static
40
     */
41 8
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
42
    {
43 8
        $aggregateRoot = new static($aggregateRootId);
44
45
        /** @var Event $event */
46 8
        foreach ($events as $event) {
47 2
            $aggregateRoot->apply($event);
48 2
            $aggregateRoot->aggregateRootVersion++;
49
        }
50
51 8
        return $aggregateRoot;
52
    }
53
54
    abstract protected function apply(Event $event);
55
}