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

reconstituteFromSnapshotAndEvents()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 2
b 0
f 0
nc 2
nop 2
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 3
rs 10
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