|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Krenor\Prometheus\Storage\Repositories; |
|
4
|
|
|
|
|
5
|
|
|
use RuntimeException; |
|
6
|
|
|
use Tightenco\Collect\Support\Collection; |
|
7
|
|
|
use Krenor\Prometheus\Contracts\Repository; |
|
8
|
|
|
|
|
9
|
|
|
class ApcuRepository implements Repository |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* {@inheritdoc} |
|
13
|
|
|
*/ |
|
14
|
|
|
public function get(string $key): Collection |
|
15
|
|
|
{ |
|
16
|
|
|
return new Collection(apcu_fetch($key) ?: []); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* {@inheritdoc} |
|
21
|
|
|
*/ |
|
22
|
|
|
public function increment(string $key, string $field, float $value): void |
|
23
|
|
|
{ |
|
24
|
|
|
$collection = $this->get($key); |
|
25
|
|
|
|
|
26
|
|
|
$stored = apcu_store($key, $collection->put( |
|
27
|
|
|
$field, |
|
28
|
|
|
$collection->get($field, 0) + $value |
|
29
|
|
|
)); |
|
30
|
|
|
|
|
31
|
|
|
if (!$stored) { |
|
32
|
|
|
throw new RuntimeException('`apcu_store` returned false.'); |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* {@inheritdoc} |
|
38
|
|
|
*/ |
|
39
|
|
|
public function decrement(string $key, string $field, float $value) |
|
40
|
|
|
{ |
|
41
|
|
|
$this->increment($key, $field, -abs($value)); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* {@inheritdoc} |
|
46
|
|
|
*/ |
|
47
|
|
|
public function set(string $key, string $field, $value, $override = true) |
|
48
|
|
|
{ |
|
49
|
|
|
$collection = $this->get($key); |
|
50
|
|
|
|
|
51
|
|
|
if (!$override && $this->get($key)->get($field) !== null) { |
|
52
|
|
|
return; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$stored = apcu_store($key, $collection->put($field, $value)); |
|
56
|
|
|
|
|
57
|
|
|
if (!$stored) { |
|
58
|
|
|
throw new RuntimeException('`apcu_store` returned false.'); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* {@inheritdoc} |
|
64
|
|
|
*/ |
|
65
|
|
|
public function push(string $key, float $value) |
|
66
|
|
|
{ |
|
67
|
|
|
$collection = $this->get($key); |
|
68
|
|
|
|
|
69
|
|
|
$stored = apcu_store($key, $collection->push($value)); |
|
70
|
|
|
|
|
71
|
|
|
if (!$stored) { |
|
72
|
|
|
throw new RuntimeException('`apcu_store` returned false.'); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|