SnapshotRepository::persist()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 7
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Chocofamily\LaravelEventSauce;
4
5
use EventSauce\EventSourcing\AggregateRootId;
6
use EventSauce\EventSourcing\Snapshotting\Snapshot;
7
use EventSauce\EventSourcing\Snapshotting\SnapshotRepository as EventSauceSnapshotRepository;
8
use Illuminate\Database\Connection;
9
use Illuminate\Support\Carbon;
10
11
class SnapshotRepository implements EventSauceSnapshotRepository
12
{
13
    /** @var Connection */
14
    protected $connection;
15
16
    /** @var string */
17
    protected $table;
18
19
    public function __construct(Connection $connection, string $table)
20
    {
21
        $this->connection = $connection;
22
23
        $this->table = $table;
24
    }
25
26
    public function persist(Snapshot $snapshot): void
27
    {
28
        $this->connection
29
            ->table($this->table)
30
            ->insert([
31
                'aggregate_root_id'         =>  $snapshot->aggregateRootId()->toString(),
32
                'aggregate_root_version'    =>  $snapshot->aggregateRootVersion(),
33
                'state'                     =>  json_encode($snapshot->state()),
34
                'recorded_at'               =>  Carbon::now()->toDateTimeString(),
35
            ]);
36
    }
37
38
    public function retrieve(AggregateRootId $id): ?Snapshot
39
    {
40
        $snapshot = $this->connection
41
            ->table($this->table)
42
            ->where('aggregate_root_id', $id->toString())
43
            ->first();
44
45
        if (is_null($snapshot)) {
46
            return null;
47
        }
48
49
        return new Snapshot(
50
            $id,
51
            $snapshot->aggregate_root_version,
52
            json_decode($snapshot->state)
53
        );
54
    }
55
}
56