Completed
Push — master ( 79a39e...bcea06 )
by Dan
02:46
created

GuzzleFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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();
27
        $reactAwareCurlFactory = $clientFactory->createReactAwareCurlFactory($this->eventLoop, null, $this->logger);
28
        $handler = $reactAwareCurlFactory->getHandler();
29
        $handlerStack =  $this->createHandlerStack($handler);
30
        $config['handler'] = $handlerStack;
31
32
        return new Client($config);
33
    }
34
35
    /**
36
     * Like HandlerStack::create() except no http_errors
37
     *
38
     * @param CurlMultiHandler $handler
39
     * @return HandlerStack
40
     */
41
    public function createHandlerStack(CurlMultiHandler $handler) : HandlerStack
42
    {
43
        $stack = new HandlerStack($handler);
44
        $stack->push(Middleware::redirect(), 'allow_redirects');
45
        $stack->push(Middleware::cookies(), 'cookies');
46
        $stack->push(Middleware::prepareBody(), 'prepare_body');
47
48
        return $stack;
49
    }
50
}