1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JVelasco\CircuitBreaker\AvailabilityStrategy; |
4
|
|
|
|
5
|
|
|
use JVelasco\CircuitBreaker\AvailabilityStrategy; |
6
|
|
|
use JVelasco\CircuitBreaker\StorageException; |
7
|
|
|
|
8
|
|
|
class InMemoryStorage implements Storage |
9
|
|
|
{ |
10
|
|
|
private $numberOfFailures = []; |
11
|
|
|
private $strategyData = []; |
12
|
|
|
private $throwExceptionInNumberOfFailures; |
13
|
|
|
|
14
|
5 |
|
public function numberOfFailures(string $serviceName): int |
15
|
|
|
{ |
16
|
5 |
|
if ($this->throwExceptionInNumberOfFailures) { |
17
|
1 |
|
throw new StorageException(); |
18
|
|
|
} |
19
|
|
|
|
20
|
4 |
|
return (int) $this->numberOfFailures[$serviceName]; |
21
|
|
|
} |
22
|
|
|
|
23
|
2 |
|
public function resetFailuresCounter(string $serviceName) |
24
|
|
|
{ |
25
|
2 |
|
$this->numberOfFailures[$serviceName] = 0; |
26
|
2 |
|
} |
27
|
|
|
|
28
|
3 |
|
public function saveStrategyData( |
29
|
|
|
AvailabilityStrategy $strategy, |
30
|
|
|
string $serviceName, |
31
|
|
|
string $key, |
32
|
|
|
string $value |
33
|
|
|
) { |
34
|
3 |
|
if (!isset($this->strategyData[$strategy->getId()])) { |
35
|
3 |
|
$this->strategyData[$strategy->getId()] = [$serviceName => []]; |
36
|
2 |
|
} elseif (!isset($this->strategyData[$strategy->getId()][$serviceName])) { |
37
|
|
|
$this->strategyData[$strategy->getId()][$serviceName] = []; |
38
|
|
|
} |
39
|
|
|
|
40
|
3 |
|
$this->strategyData[$strategy->getId()][$serviceName][$key] = $value; |
41
|
3 |
|
} |
42
|
|
|
|
43
|
3 |
|
public function getStrategyData( |
44
|
|
|
AvailabilityStrategy $strategy, |
45
|
|
|
string $serviceName, |
46
|
|
|
string $key |
47
|
|
|
): string |
48
|
|
|
{ |
49
|
3 |
|
if (empty($this->strategyData[$strategy->getId()][$serviceName][$key])) { |
50
|
3 |
|
return ""; |
51
|
|
|
} |
52
|
|
|
|
53
|
3 |
|
return $this->strategyData[$strategy->getId()][$serviceName][$key]; |
54
|
|
|
} |
55
|
|
|
|
56
|
4 |
|
public function setNumberOfFailures($serviceName, $numberOfFailures) |
57
|
|
|
{ |
58
|
4 |
|
$this->numberOfFailures[$serviceName] = $numberOfFailures; |
59
|
4 |
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
1 |
|
public function throwExceptionInNumberOfFailures() |
63
|
|
|
{ |
64
|
1 |
|
$this->throwExceptionInNumberOfFailures = true; |
65
|
1 |
|
} |
66
|
|
|
} |
67
|
|
|
|