CacheCircuitBreakerStore::isAvailable()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 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