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