HttpClient::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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