Completed
Push — master ( 55dded...2df39b )
by Jorge
01:37
created

SharedStorage   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 47
rs 10
c 0
b 0
f 0
ccs 23
cts 23
cp 1
wmc 9

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A saveStrategyData() 0 3 1
A numberOfFailures() 0 3 1
A getStrategyData() 0 3 1
A keyForStrategyData() 0 3 1
A counterKeyForService() 0 3 1
A incrementFailures() 0 3 1
A decrementFailures() 0 7 2
1
<?php
2
3
namespace JVelasco\CircuitBreaker\APCu;
4
5
use JVelasco\CircuitBreaker\AvailabilityStrategy;
6
use JVelasco\CircuitBreaker\AvailabilityStrategy\Storage;
7
use \JVelasco\CircuitBreaker\FailuresCounterStorage;
8
9
final class SharedStorage implements FailuresCounterStorage, Storage
10
{
11
    private $failuresCounterPrefix;
12
13 5
    public function __construct(string $failuresCounterPrefix = "cb_failures")
14
    {
15 5
        $this->failuresCounterPrefix = $failuresCounterPrefix;
16 5
    }
17
18 2
    public function incrementFailures(string $serviceName)
19
    {
20 2
        apcu_inc($this->counterKeyForService($serviceName));
21 2
    }
22
23 2
    public function decrementFailures(string $serviceName)
24
    {
25 2
        $counterKey = $this->counterKeyForService($serviceName);
26 2
        $newValue = apcu_dec($counterKey);
27
28 2
        if ($newValue < 0) {
29 1
            apcu_store($counterKey, 0);
30
        }
31 2
    }
32
33 1
    public function numberOfFailures(string $serviceName): int
34
    {
35 1
        return apcu_fetch($this->counterKeyForService($serviceName));
36
    }
37
38 1
    public function saveStrategyData(AvailabilityStrategy $strategy, string $key, string $value)
39
    {
40 1
        apcu_store($this->keyForStrategyData($strategy, $key), $value);
41 1
    }
42
43 1
    public function getStrategyData(AvailabilityStrategy $strategy, string $key): string
44
    {
45 1
        return apcu_fetch($this->keyForStrategyData($strategy, $key));
46
    }
47
48 4
    private function counterKeyForService(string $serviceName): string
49
    {
50 4
        return sprintf("%s.%s", $this->failuresCounterPrefix, $serviceName);
51
    }
52
53 1
    private function keyForStrategyData(AvailabilityStrategy $strategy, string $key): string
54
    {
55 1
        return sprintf("%s.%s", $strategy->getId(), $key);
56
    }
57
}
58