Passed
Push — master ( cbefbc...3619f4 )
by Frank
16:49 queued 06:49
created

SnapshottingBehaviour::createSnapshot()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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 positive-int|0
0 ignored issues
show
Documentation Bug introduced by
The doc comment positive-int|0 at position 0 could not be parsed: Unknown type name 'positive-int' at position 0 in positive-int|0.
Loading history...
15
     */
16
    private int $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(): mixed;
30
31
    public static function reconstituteFromSnapshotAndEvents(Snapshot $snapshot, Generator $events): static
32
    {
33
        $id = $snapshot->aggregateRootId();
34 1
        /** @var static&AggregateRoot $aggregateRoot */
35
        $aggregateRoot = static::reconstituteFromSnapshotState($id, $snapshot->state());
36 1
        $aggregateRoot->aggregateRootVersion = $snapshot->aggregateRootVersion();
37
38 1
        foreach ($events as $event) {
39 1
            $aggregateRoot->apply($event);
40
        }
41 1
42 1
        $aggregateRoot->aggregateRootVersion = $events->getReturn() ?: $aggregateRoot->aggregateRootVersion;
43
44
        return $aggregateRoot;
45 1
    }
46
47 1
    abstract protected static function reconstituteFromSnapshotState(AggregateRootId $id, $state): AggregateRootWithSnapshotting;
48
}
49