Completed
Push — develop ( 6a297d...d2d4a3 )
by Stan
02:17
created

MemcachedRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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