GuzzleFactory::newClient()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
namespace Nopolabs\Yabot\Guzzle;
3
4
use GuzzleHttp\Client;
5
use GuzzleHttp\Handler\CurlMultiHandler;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Middleware;
8
use Nopolabs\ReactAwareGuzzleClientFactory;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\NullLogger;
11
use React\EventLoop\LoopInterface;
12
13
class GuzzleFactory
14
{
15
    private $eventLoop;
16
    private $logger;
17
18
    public function __construct(LoopInterface $eventLoop, LoggerInterface $logger = null)
19
    {
20
        $this->eventLoop = $eventLoop;
21
        $this->logger = $logger ?? new NullLogger();
22
    }
23
24
    public function newClient(array $config) : Client
25
    {
26
        $clientFactory = new ReactAwareGuzzleClientFactory(function(CurlMultiHandler $handler) {
27
            return $this->createHandlerStack($handler);
28
        });
29
30
        return $clientFactory->createGuzzleClient($this->eventLoop, $config, null, $this->logger);
31
    }
32
33
    /**
34
     * Like HandlerStack::create() except no http_errors
35
     * @see http://docs.guzzlephp.org/en/stable/request-options.html#http-errors
36
     *
37
     * @param CurlMultiHandler $handler
38
     * @return HandlerStack
39
     */
40
    public function createHandlerStack(CurlMultiHandler $handler) : HandlerStack
41
    {
42
        $stack = new HandlerStack($handler);
43
        $stack->push(Middleware::redirect(), 'allow_redirects');
44
        $stack->push(Middleware::cookies(), 'cookies');
45
        $stack->push(Middleware::prepareBody(), 'prepare_body');
46
47
        return $stack;
48
    }
49
}