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

EloquentSnapshotRepository::retrieve()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 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