|
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
|
|
|
|