Completed
Push — master ( 48251c...04d465 )
by David
04:13
created

Client::buildResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 9.4285
cc 1
eloc 10
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Http\Adapter\React;
4
5
use Http\Client\HttpClient;
6
use Http\Client\HttpAsyncClient;
7
use Http\Client\Exception\HttpException;
8
use Http\Client\Exception\RequestException;
9
use Http\Discovery\MessageFactoryDiscovery;
10
use Http\Discovery\StreamFactoryDiscovery;
11
use Http\Message\ResponseFactory;
12
use Http\Message\StreamFactory;
13
use Psr\Http\Message\RequestInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\StreamInterface;
16
use React\EventLoop\LoopInterface;
17
use React\HttpClient\Client as ReactClient;
18
use React\HttpClient\Request as ReactRequest;
19
use React\HttpClient\Response as ReactResponse;
20
21
/**
22
 * Client for the React promise implementation.
23
 *
24
 * @author Stéphane Hulard <[email protected]>
25
 */
26
class Client implements HttpClient, HttpAsyncClient
27
{
28
    /**
29
     * React HTTP client.
30
     *
31
     * @var Client
32
     */
33
    private $client;
34
35
    /**
36
     * React event loop.
37
     *
38
     * @var LoopInterface
39
     */
40
    private $loop;
41
42
    /**
43
     * @var ResponseFactory
44
     */
45
    private $responseFactory;
46
47
    /**
48
     * @var StreamFactory
49
     */
50
    private $streamFactory;
51
52
    /**
53
     * Initialize the React client.
54
     *
55
     * @param ResponseFactory|null $responseFactory
56
     * @param LoopInterface|null   $loop
57
     * @param ReactClient|null     $client
58
     * @param StreamFactory|null   $streamFactory
59
     */
60 108
    public function __construct(
61
        ResponseFactory $responseFactory = null,
62
        LoopInterface $loop = null,
63
        ReactClient $client = null,
64
        StreamFactory $streamFactory = null
65
    ) {
66 108
        if (null !== $client && null === $loop) {
67
            throw new \RuntimeException(
68
                'You must give a LoopInterface instance with the Client'
69
            );
70
        }
71
72 108
        $this->loop = $loop ?: ReactFactory::buildEventLoop();
73 108
        $this->client = $client ?: ReactFactory::buildHttpClient($this->loop);
0 ignored issues
show
Documentation Bug introduced by
It seems like $client ?: \Http\Adapter...HttpClient($this->loop) of type object<React\HttpClient\Client> is incompatible with the declared type object<Http\Adapter\React\Client> of property $client.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
74
75 108
        $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find();
76 108
        $this->streamFactory = $streamFactory ?: StreamFactoryDiscovery::find();
77 108
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82 53
    public function sendRequest(RequestInterface $request)
83
    {
84 53
        $promise = $this->sendAsyncRequest($request);
85
86 53
        return $promise->wait();
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92 108
    public function sendAsyncRequest(RequestInterface $request)
93
    {
94 108
        $reactRequest = $this->buildReactRequest($request);
95 108
        $promise = new Promise($this->loop);
96
97
        $reactRequest->on('error', function (\Exception $error) use ($promise, $request) {
98 3
            $promise->reject(new RequestException(
99 3
                $error->getMessage(),
100 3
                $request,
101
                $error
102 3
            ));
103 108
        });
104
105
        $reactRequest->on('response', function (ReactResponse $reactResponse = null) use ($promise, $request) {
106 105
            $bodyStream = $this->streamFactory->createStream();
107
            $reactResponse->on('data', function ($data) use (&$bodyStream) {
0 ignored issues
show
Bug introduced by
It seems like $reactResponse is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
108 105
                $bodyStream->write((string) $data);
109 105
            });
110
111 105
            $reactResponse->on('end', function (\Exception $error = null) use ($promise, $request, $reactResponse, &$bodyStream) {
0 ignored issues
show
Bug introduced by
It seems like $reactResponse is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
112 105
                $response = $this->buildResponse(
113 105
                    $reactResponse,
0 ignored issues
show
Bug introduced by
It seems like $reactResponse defined by parameter $reactResponse on line 105 can be null; however, Http\Adapter\React\Client::buildResponse() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
114
                    $bodyStream
115 105
                );
116 105
                if (null !== $error) {
117
                    $promise->reject(new HttpException(
118
                        $error->getMessage(),
119
                        $request,
120
                        $response,
121
                        $error
122
                    ));
123
                } else {
124 105
                    $promise->resolve($response);
125
                }
126 105
            });
127 108
        });
128
129 108
        $reactRequest->end((string) $request->getBody());
130
131 108
        return $promise;
132
    }
133
134
    /**
135
     * Build a React request from the PSR7 RequestInterface.
136
     *
137
     * @param RequestInterface $request
138
     *
139
     * @return ReactRequest
140
     */
141 108
    private function buildReactRequest(RequestInterface $request)
142
    {
143 108
        $headers = [];
144
145 108
        foreach ($request->getHeaders() as $name => $value) {
146 108
            $headers[$name] = (is_array($value) ? $value[0] : $value);
147 108
        }
148
149 108
        $reactRequest = $this->client->request(
0 ignored issues
show
Bug introduced by
The method request() does not exist on Http\Adapter\React\Client. Did you maybe mean sendRequest()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
150 108
            $request->getMethod(),
151 108
            (string) $request->getUri(),
152 108
            $headers,
153 108
            $request->getProtocolVersion()
154 108
        );
155
156 108
        return $reactRequest;
157
    }
158
159
    /**
160
     * Transform a React Response to a valid PSR7 ResponseInterface instance.
161
     *
162
     * @param ReactResponse   $response
163
     * @param StreamInterface $body
164
     *
165
     * @return ResponseInterface
166
     */
167 105
    private function buildResponse(
168
        ReactResponse $response,
169
        StreamInterface $body
170
    ) {
171 105
        $body->rewind();
172
173 105
        return $this->responseFactory->createResponse(
174 105
            $response->getCode(),
175 105
            $response->getReasonPhrase(),
176 105
            $response->getHeaders(),
177 105
            $body,
178 105
            $response->getVersion()
179 105
        );
180
    }
181
}
182