CacheCircuitBreakerStore   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 38
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isAvailable() 0 4 1
A reportFailure() 0 14 3
A reportSuccess() 0 5 1
1
<?php
2
3
namespace FrancescoMalatesta\LaravelCircuitBreaker\Store;
4
5
use Illuminate\Cache\Repository as Cache;
6
7
class CacheCircuitBreakerStore implements CircuitBreakerStoreInterface
8
{
9
    const KEY_BASE = 'circuit_breaker_';
10
11
    /** @var Cache */
12
    private $cache;
13
14
    public function __construct(Cache $cache)
15
    {
16
        $this->cache = $cache;
17
    }
18
19
    public function isAvailable(string $identifier): bool
20
    {
21
        return !($this->cache->has(self::KEY_BASE . $identifier . '_failed'));
22
    }
23
24
    public function reportFailure(string $identifier, int $attemptsThreshold, int $attemptsTtl, int $failureTtl): void
25
    {
26
        $key = self::KEY_BASE . $identifier . '_remaining_attempts';
27
28
        if (!$this->cache->has($key)) {
29
            $this->cache->set($key, $attemptsThreshold, $attemptsTtl);
30
            return;
31
        }
32
33
        $remainingAttempts = $this->cache->decrement($key);
34
        if ($remainingAttempts === 0) {
35
            $this->cache->set(self::KEY_BASE . $identifier . '_failed', true, $failureTtl);
36
        }
37
    }
38
39
    public function reportSuccess(string $identifier): void
40
    {
41
        $this->cache->forget(self::KEY_BASE . $identifier . '_remaining_attempts');
42
        $this->cache->forget(self::KEY_BASE . $identifier . '_failed');
43
    }
44
}
45