createGuzzleClient()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 4
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
1
<?php
2
3
namespace Nopolabs;
4
5
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Handler\CurlFactory;
8
use GuzzleHttp\Handler\CurlMultiHandler;
9
use GuzzleHttp\HandlerStack;
10
use Psr\Log\LoggerInterface;
11
use React\EventLoop\LoopInterface;
12
13
class ReactAwareGuzzleClientFactory
14
{
15
    private $createHandlerStack;
16
17
    public function __construct(callable $createHandlerStack = null)
18
    {
19
        $this->createHandlerStack = $createHandlerStack;
20
    }
21
22
    public function createGuzzleClient(
23
        LoopInterface $eventLoop,
24
        array $config = [],
25
        CurlFactory $curlFactory = null,
26
        LoggerInterface $logger = null
27
    ) : Client
28
    {
29
        $reactAwareCurlFactory = $this->createReactAwareCurlFactory($eventLoop, $curlFactory, $logger);
30
31
        $handler = $reactAwareCurlFactory->getHandler();
32
33
        $handlerStack = $this->createHandlerStack($handler);
34
35
        $config['handler'] = $handlerStack;
36
37
        return new Client($config);
38
    }
39
40
    public function createReactAwareCurlFactory(
41
        LoopInterface $eventLoop,
42
        CurlFactory $curlFactory = null,
43
        LoggerInterface $logger = null
44
    ) : ReactAwareCurlFactory
45
    {
46
        $curlFactory = $curlFactory ?? new CurlFactory(50);
47
        $reactAwareCurlFactory = new ReactAwareCurlFactory($eventLoop, $curlFactory, $logger);
48
        $handler = new CurlMultiHandler(['handle_factory' => $reactAwareCurlFactory]);
49
        $reactAwareCurlFactory->setHandler($handler);
50
51
        return $reactAwareCurlFactory;
52
    }
53
54
    private function createHandlerStack(CurlMultiHandler $handler)
55
    {
56
        if ($this->createHandlerStack) {
57
            $create = $this->createHandlerStack;
58
            return $create($handler);
59
        }
60
61
        return HandlerStack::create($handler);
62
    }
63
}