Completed
Pull Request — master (#131)
by Eric
63:39 queued 61:20
created

PeclHttpAdapter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
ccs 4
cts 5
cp 0.8
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
crap 2.032
1
<?php
2
3
/*
4
 * This file is part of the Ivory Http Adapter package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\HttpAdapter;
13
14
use http\Client;
15
use http\Client\Request;
16
use http\Message\Body;
17
use Ivory\HttpAdapter\Message\InternalRequestInterface;
18
19
/**
20
 * @author GeLo <[email protected]>
21
 */
22
class PeclHttpAdapter extends AbstractHttpAdapter
23
{
24
    /**
25
     * @var Client
26
     */
27
    private $client;
28
29
    /**
30
     * @param Client                 $client
31
     * @param ConfigurationInterface $configuration
32
     */
33 14
    public function __construct(Client $client = null, ConfigurationInterface $configuration = null)
34
    {
35 14
        parent::__construct($configuration);
36
37 14
        $this->client = $client ?: new Client();
38 14
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected function sendInternalRequest(InternalRequestInterface $internalRequest)
44
    {
45
        $body = new Body();
46
        $body->append($this->prepareBody($internalRequest));
47
48
        $request = new Request(
49
            $internalRequest->getMethod(),
50
            $uri = (string) $internalRequest->getUri(),
51
            $this->prepareHeaders($internalRequest),
52
            $body
53
        );
54
55
        $httpVersion = $internalRequest->getProtocolVersion() === InternalRequestInterface::PROTOCOL_VERSION_1_0
56
            ? \http\Client\Curl\HTTP_VERSION_1_0
57
            : \http\Client\Curl\HTTP_VERSION_1_1;
58
59
        $request->setOptions([
60
            'protocol' => $httpVersion,
61
            'timeout'  => $this->getConfiguration()->getTimeout(),
62
        ]);
63
64
        try {
65
            $this->client->reset()->enqueue($request)->send();
66
        } catch (\Exception $e) {
67
            throw HttpAdapterException::cannotFetchUri($uri, $this->getName(), $e->getMessage());
68
        }
69
70
        $response = $this->client->getResponse();
71
72
        return $this->getConfiguration()->getMessageFactory()->createResponse(
73
            $response->getResponseCode(),
74
            $response->getHttpVersion(),
75
            $response->getHeaders(),
76
            $response->getBody()->getResource()
77
        );
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function getName()
84
    {
85
        return 'pecl_http';
86
    }
87
}
88