Passed
Push — master ( 50c06c...19d06a )
by Jorge
01:44
created

FixedWaitTimeToRetry::now()   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 0
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\AvailabilityStrategy;
4
5
use JVelasco\CircuitBreaker\AvailabilityStrategy;
6
use JVelasco\CircuitBreaker\StorageException;
7
8
final class FixedWaitTimeToRetry implements AvailabilityStrategy
9
{
10
    private $storage;
11
    private $maxFailures;
12
    private $waitTime;
13
14 5
    public function __construct(Storage $storage, int $maxFailures, int $waitTime)
15
    {
16 5
        $this->storage = $storage;
17 5
        $this->maxFailures = $maxFailures;
18 5
        $this->waitTime = $waitTime;
19 5
    }
20
21 5
    public function isAvailable(string $serviceName): bool
22
    {
23
        try {
24 5
            if ($this->storage->numberOfFailures($serviceName) < $this->maxFailures) {
25 2
                return true;
26
            }
27
28 3
            $lastRetry = $this->getLastTryTime();
29 3
            if ($this->now() - $lastRetry > $this->waitTime) {
30 1
                $this->storage->resetFailuresCounter($serviceName);
31 1
                return true;
32
            }
33
34 2
            return false;
35 1
        } catch (StorageException $ex) {
36 1
            return true;
37
        }
38
    }
39
40 1
    public function getId(): string
41
    {
42 1
        return "fixed_time_to_retry";
43
    }
44
45 3
    private function getLastTryTime(): int
46
    {
47 3
        $lastTryTimestamp = $this->storage->getStrategyData($this, "last_try");
48 3
        return $lastTryTimestamp ? $lastTryTimestamp : $this->now();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $lastTryTimestamp...imestamp : $this->now() could return the type string which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
49
    }
50
51 3
    private function now(): int
52
    {
53 3
        return floor(microtime(true) * 1000);
0 ignored issues
show
Bug Best Practice introduced by
The expression return floor(microtime(true) * 1000) returns the type double which is incompatible with the type-hinted return integer.
Loading history...
54
    }
55
}
56