Passed
Push — master ( 886788...7f76db )
by Leonardo
01:39 queued 11s
created

myService()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 2
nc 2
nop 0
1
<?php
2
require_once __DIR__ . '/../vendor/autoload.php';
3
4
use LeoCarmo\CircuitBreaker\CircuitBreaker;
5
6
// Connect to redis
7
$redis = new \Redis();
8
$redis->connect('localhost', 6379);
9
10
$adapter = new \LeoCarmo\CircuitBreaker\Adapters\RedisAdapter($redis, 'my-product');
11
12
// Set redis adapter for CB
13
CircuitBreaker::setAdapter($adapter);
14
15
// Configure settings for CB
16
CircuitBreaker::setGlobalSettings([
17
    'timeWindow' => 60, // Time for an open circuit (seconds)
18
    'failureRateThreshold' => 50, // Fail rate for open the circuit
19
    'intervalToHalfOpen' => 30,  // Half open time (seconds)
20
]);
21
22
// Configure settings for specific service
23
CircuitBreaker::setServiceSettings('my-custom-service', [
24
    'timeWindow' => 30, // Time for an open circuit (seconds)
25
    'failureRateThreshold' => 15, // Fail rate for open the circuit
26
    'intervalToHalfOpen' => 10,  // Half open time (seconds)
27
]);
28
29
// Check circuit status for service: `my-service`
30
if (! CircuitBreaker::isAvailable('my-service')) {
31
    die('Circuit is not available!');
32
}
33
34
// Usage example for success and failure
35
function myService() {
36
    if (rand(1, 100) >= 50) {
37
        throw new RuntimeException('Something got wrong!');
38
    }
39
}
40
41
try {
42
    myService();
43
    CircuitBreaker::success('my-service');
44
} catch (RuntimeException $e) {
45
    // If an error occurred, it must be recorded as failure.
46
    CircuitBreaker::failure('my-service');
47
    die($e->getMessage());
48
}