Passed
Pull Request — master (#66)
by Frank
03:02 queued 52s
created

SnapshottingBehaviour   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 9
c 4
b 0
f 0
dl 0
loc 38
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
    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