Passed
Push — master ( dbfb37...74a6ed )
by Frank
46s queued 13s
created

SnapshottingBehaviour   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 10
c 5
b 0
f 0
dl 0
loc 43
ccs 10
cts 10
cp 1
rs 10
wmc 4

2 Methods

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