HttpClient   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 30
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getRetryMiddleware() 0 15 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Incapsula;
6
7
use GuzzleHttp\Client as GuzzleClient;
8
use GuzzleHttp\Exception\ConnectException;
9
use GuzzleHttp\Handler\CurlHandler;
10
use GuzzleHttp\HandlerStack;
11
use GuzzleHttp\Middleware;
12
13
class HttpClient extends GuzzleClient
14
{
15
    /**
16
     * @var int[]
17
     */
18
    private $retryStatusCodes = [500, 502, 503, 504, 429];
19
20
    public function __construct(array $config = [])
21
    {
22
        $handler = HandlerStack::create(new CurlHandler());
23
        $handler->push($this->getRetryMiddleware());
24
25
        parent::__construct(array_merge($config, ['handler' => $handler]));
26
    }
27
28
    private function getRetryMiddleware(): callable
29
    {
30
        return Middleware::retry(
31
            function ($retries, $request, $response, $exception) {
32
                if ($retries > 10) {
33
                    return false;
34
                }
35
                if ($exception instanceof ConnectException) {
36
                    return true;
37
                }
38
                if ($response && \in_array($response->getStatusCode(), $this->retryStatusCodes, true)) {
39
                    return true;
40
                }
41
42
                return false;
43
            }
44
        );
45
    }
46
}
47