Completed
Pull Request — master (#51)
by Freek
01:20
created

EloquentSnapshotRepository   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 39
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A retrieve() 0 11 2
A persist() 0 13 1
1
<?php
2
3
namespace Spatie\EventSourcing\Snapshots;
4
5
use Spatie\EventSourcing\Exceptions\InvalidEloquentSnapshotModel;
6
use Spatie\EventSourcing\Snapshots\EloquentSnapshot;
7
use Spatie\EventSourcing\Snapshots\Snapshot;
8
use Spatie\EventSourcing\Snapshots\SnapshotRepository;
9
10
class EloquentSnapshotRepository implements SnapshotRepository
11
{
12
    protected $snapshotModel;
13
14
    public function __construct()
15
    {
16
        $this->snapshotModel = config('event-sourcing.snapshot_model', EloquentSnapshot::class);
17
18
        if (! new $this->snapshotModel instanceof EloquentSnapshot) {
19
            throw new InvalidEloquentSnapshotModel("The class {$this->snapshotModel} must extend EloquentSnapshot");
20
        }
21
    }
22
23
    public function retrieve(string $aggregateUuid): ?Snapshot
24
    {
25
        /** @var \Illuminate\Database\Query\Builder $query */
26
        $query = $this->snapshotModel::query();
27
28
        if ($snapshot = $query->latest()->uuid($aggregateUuid)->first()) {
29
            return $snapshot->toSnapshot();
30
        }
31
32
        return null;
33
    }
34
35
    public function persist(Snapshot $snapshot): Snapshot
36
    {
37
        /** @var EloquentSnapshot $eloquentSnapshot */
38
        $eloquentSnapshot = new $this->snapshotModel();
39
40
        $eloquentSnapshot->aggregate_uuid = $snapshot->aggregateUuid;
41
        $eloquentSnapshot->aggregate_version = $snapshot->aggregateVersion;
42
        $eloquentSnapshot->state = $snapshot->state;
43
44
        $eloquentSnapshot->save();
45
46
        return $eloquentSnapshot->toSnapshot();
47
    }
48
}
49