Client::sendRequest()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Http\Adapter\Guzzle5;
4
5
use GuzzleHttp\Client as GuzzleClient;
6
use GuzzleHttp\ClientInterface;
7
use GuzzleHttp\Message\RequestInterface as GuzzleRequest;
8
use GuzzleHttp\Message\ResponseInterface as GuzzleResponse;
9
use Http\Client\HttpClient;
10
use Http\Discovery\MessageFactoryDiscovery;
11
use Http\Message\ResponseFactory;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
use Http\Client\Exception as HttplugException;
15
use GuzzleHttp\Exception as GuzzleExceptions;
16
17
/**
18
 * @author GeLo <[email protected]>
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
class Client implements HttpClient
22
{
23
    /**
24
     * @var ClientInterface
25
     */
26
    private $client;
27
28
    /**
29
     * @var ResponseFactory
30
     */
31
    private $responseFactory;
32
33
    /**
34
     * @param ClientInterface|null $client
35
     * @param ResponseFactory|null $responseFactory
36
     */
37 168
    public function __construct(ClientInterface $client = null, ResponseFactory $responseFactory = null)
38
    {
39 168
        $this->client = $client ?: new GuzzleClient();
40 168
        $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find();
41 168
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 168
    public function sendRequest(RequestInterface $request): ResponseInterface
47
    {
48 168
        $guzzleRequest = $this->createRequest($request);
49
50
        try {
51 168
            $response = $this->client->send($guzzleRequest);
52 15
        } catch (GuzzleExceptions\TransferException $e) {
53 15
            throw $this->handleException($e, $request);
54
        }
55
56 153
        return $this->createResponse($response);
57
    }
58
59
    /**
60
     * Converts a PSR request into a Guzzle request.
61
     *
62
     * @param RequestInterface $request
63
     *
64
     * @return GuzzleRequest
65
     */
66 168
    private function createRequest(RequestInterface $request)
67
    {
68
        $options = [
69 168
            'exceptions' => false,
70
            'allow_redirects' => false,
71
        ];
72
73 168
        $options['version'] = $request->getProtocolVersion();
74 168
        $options['headers'] = $request->getHeaders();
75 168
        $body = (string) $request->getBody();
76 168
        $options['body'] = '' === $body ? null : $body;
77
78 168
        return $this->client->createRequest(
79 168
            $request->getMethod(),
80 168
            (string) $request->getUri(),
81 168
            $options
82
        );
83
    }
84
85
    /**
86
     * Converts a Guzzle response into a PSR response.
87
     *
88
     * @param GuzzleResponse $response
89
     *
90
     * @return ResponseInterface
91
     */
92 157
    private function createResponse(GuzzleResponse $response)
93
    {
94 157
        $body = $response->getBody();
95
96 157
        return $this->responseFactory->createResponse(
97 157
            $response->getStatusCode(),
98 157
            null,
99 157
            $response->getHeaders(),
100 157
            isset($body) ? $body->detach() : null,
101 157
            $response->getProtocolVersion()
102
        );
103
    }
104
105
    /**
106
     * Converts a Guzzle exception into an Httplug exception.
107
     *
108
     * @param GuzzleExceptions\TransferException $exception
109
     * @param RequestInterface                   $request
110
     *
111
     * @return HttplugException
112
     */
113 15
    private function handleException(GuzzleExceptions\TransferException $exception, RequestInterface $request)
114
    {
115 15
        if ($exception instanceof GuzzleExceptions\ConnectException) {
116 4
            return new HttplugException\NetworkException($exception->getMessage(), $request, $exception);
117
        }
118
119 11
        if ($exception instanceof GuzzleExceptions\RequestException) {
120
            // Make sure we have a response for the HttpException
121 9
            if ($exception->hasResponse()) {
122 4
                $psr7Response = $this->createResponse($exception->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $exception->getResponse() can be null; however, createResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
123
124 4
                return new HttplugException\HttpException(
125 4
                    $exception->getMessage(),
126 4
                    $request,
127 4
                    $psr7Response,
128 4
                    $exception
129
                );
130
            }
131
132 5
            return new HttplugException\RequestException($exception->getMessage(), $request, $exception);
133
        }
134
135 2
        return new HttplugException\TransferException($exception->getMessage(), 0, $exception);
136
    }
137
}
138