Completed
Pull Request — master (#48)
by Rias
61:09 queued 59:41
created

EloquentSnapshotRepository::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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