Completed
Push — master ( 0dfb70...6f61e6 )
by Jorge
01:46
created

APCuStorage::resetFailuresCounter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
namespace JVelasco\CircuitBreaker\Adapters;
4
5
use JVelasco\CircuitBreaker\AvailabilityStrategy;
6
use JVelasco\CircuitBreaker\AvailabilityStrategy\Storage;
7
use \JVelasco\CircuitBreaker\FailuresCounterStorage;
8
9
final class APCuStorage implements FailuresCounterStorage, Storage
10
{
11
    private $failuresCounterPrefix;
12
13 7
    public function __construct(string $failuresCounterPrefix = "cb_failures")
14
    {
15 7
        $this->failuresCounterPrefix = $failuresCounterPrefix;
16 7
    }
17
18 4
    public function incrementFailures(string $serviceName)
19
    {
20 4
        apcu_inc($this->counterKeyForService($serviceName));
21 4
    }
22
23 3
    public function decrementFailures(string $serviceName)
24
    {
25 3
        $counterKey = $this->counterKeyForService($serviceName);
26 3
        $newValue = apcu_dec($counterKey);
27
28 3
        if ($newValue < 0) {
29 1
            apcu_store($counterKey, 0);
30
        }
31 3
    }
32
33 3
    public function numberOfFailures(string $serviceName): int
34
    {
35 3
        return apcu_fetch($this->counterKeyForService($serviceName));
36
    }
37
38 1
    public function saveStrategyData(
39
        AvailabilityStrategy $strategy,
40
        string $serviceName,
41
        string $key,
42
        string $value
43
    ) {
44 1
        apcu_store($this->keyForStrategyData($strategy, $serviceName, $key), $value);
45 1
    }
46
47 2
    public function getStrategyData(
48
        AvailabilityStrategy $strategy,
49
        string $serviceName,
50
        string $key
51
    ): string {
52 2
        return apcu_fetch($this->keyForStrategyData($strategy, $serviceName, $key));
53
    }
54
55 1
    public function resetFailuresCounter(string $serviceName)
56
    {
57 1
        apcu_store($this->counterKeyForService($serviceName), 0);
58 1
    }
59
60 6
    private function counterKeyForService(string $serviceName): string
61
    {
62 6
        return sprintf("%s.%s", $this->failuresCounterPrefix, $serviceName);
63
    }
64
65 2
    private function keyForStrategyData(
66
        AvailabilityStrategy $strategy,
67
        string $serviceName,
68
        string $key
69
    ): string {
70 2
        return implode(".", [$strategy->getId(), $serviceName, $key]);
71
    }
72
}
73