Completed
Push — develop ( 3605f5...4a88bc )
by Stan
04:14
created

SimpleRepository::set()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 4
dl 0
loc 10
ccs 5
cts 6
cp 0.8333
crap 4.074
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Krenor\Prometheus\Storage\Repositories;
4
5
use Tightenco\Collect\Support\Collection;
6
use Krenor\Prometheus\Contracts\Repository;
7
use Krenor\Prometheus\Exceptions\StorageException;
8
9
abstract class SimpleRepository implements Repository
10
{
11
    /**
12
     * {@inheritdoc}
13
     */
14 12
    public function get(string $key): Collection
15
    {
16 12
        return new Collection($this->retrieve($key) ?: []);
17
    }
18
19
    /**
20
     * {@inheritdoc}
21
     */
22 8
    public function increment(string $key, string $field, float $value): void
23
    {
24 8
        $collection = $this->get($key);
25
26 8
        $collection->put($field,
27 8
            $collection->get($field, 0) + $value
28
        );
29
30 8
        if (!$this->store($key, $collection)) {
31
            throw new StorageException('The storage returned `false`.');
32
        }
33 8
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 2
    public function decrement(string $key, string $field, float $value): void
39
    {
40 2
        $this->increment($key, $field, -abs($value));
41 2
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 4
    public function set(string $key, string $field, $value, $override = true): void
47
    {
48 4
        $collection = $this->get($key);
49
50 4
        if (!$override && $collection->get($field) !== null) {
51 2
            return;
52
        }
53
54 4
        if (!$this->store($key, $collection->put($field, $value))) {
55
            throw new StorageException('The storage returned `false`.');
56
        }
57 4
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 2
    public function push(string $key, float $value): void
63
    {
64 2
        $collection = $this->get($key);
65
66 2
        if (!$this->store($key, $collection->push($value))) {
67
            throw new StorageException('The storage returned `false`.');
68
        }
69 2
    }
70
71
    /**
72
     * @param string $key
73
     *
74
     * @return mixed
75
     */
76
    abstract protected function retrieve(string $key);
77
78
    /**
79
     * @param string $key
80
     * @param Collection $collection
81
     *
82
     * @return bool
83
     */
84
    abstract protected function store(string $key, Collection $collection): bool;
85
}
86