Passed
Pull Request — master (#66)
by Frank
03:02 queued 52s
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
    abstract public function aggregateRootVersion(): int;
14
15
    abstract public function aggregateRootId(): AggregateRootId;
16
17
    abstract protected function apply(object $event): void;
18
19 1
    public function createSnapshot(): Snapshot
20
    {
21 1
        return new Snapshot($this->aggregateRootId(), $this->aggregateRootVersion(), $this->createSnapshotState());
22
    }
23
24
    abstract protected function createSnapshotState();
25
26
    /**
27
     * @param Snapshot  $snapshot
28
     * @param Generator $events
29
     *
30
     * @return static
31
     */
32 1
    public static function reconstituteFromSnapshotAndEvents(Snapshot $snapshot, Generator $events): AggregateRoot
33
    {
34 1
        $id = $snapshot->aggregateRootId();
35
        /** @var static&AggregateRoot $aggregateRoot */
36 1
        $aggregateRoot = static::reconstituteFromSnapshotState($id, $snapshot->state());
37 1
        $aggregateRoot->aggregateRootVersion = $snapshot->aggregateRootVersion();
0 ignored issues
show
Bug Best Practice introduced by
The property aggregateRootVersion does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
38
39 1
        foreach ($events as $event) {
40 1
            $aggregateRoot->apply($event);
41
        }
42
43 1
        $aggregateRoot->aggregateRootVersion = $events->getReturn() ?: $aggregateRoot->aggregateRootVersion;
44
45 1
        return $aggregateRoot;
46
    }
47
48
    abstract protected static function reconstituteFromSnapshotState(AggregateRootId $id, $state): AggregateRootWithSnapshotting;
49
}
50