Completed
Pull Request — master (#18)
by Stéphane
03:01
created

Client::buildReactRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.4285
cc 3
eloc 10
nc 3
nop 1
crap 3
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\Promise\Deferred;
18
use React\HttpClient\Client as ReactClient;
19
use React\HttpClient\Request as ReactRequest;
20
use React\HttpClient\Response as ReactResponse;
21
22
/**
23
 * Client for the React promise implementation.
24
 *
25
 * @author Stéphane Hulard <[email protected]>
26
 */
27
class Client implements HttpClient, HttpAsyncClient
28
{
29
    /**
30
     * React HTTP client.
31
     *
32
     * @var Client
33
     */
34
    private $client;
35
36
    /**
37
     * React event loop.
38
     *
39
     * @var LoopInterface
40
     */
41
    private $loop;
42
43
    /**
44
     * @var ResponseFactory
45
     */
46
    private $responseFactory;
47
48
    /**
49
     * @var StreamFactory
50
     */
51
    private $streamFactory;
52
53
    /**
54
     * Initialize the React client.
55
     *
56
     * @param ResponseFactory|null $responseFactory
57
     * @param LoopInterface|null   $loop
58
     * @param ReactClient|null     $client
59
     * @param StreamFactory|null   $streamFactory
60
     */
61 108
    public function __construct(
62 1
        ResponseFactory $responseFactory = null,
63
        LoopInterface $loop = null,
64
        ReactClient $client = null,
65
        StreamFactory $streamFactory = null
66
    ) {
67 108
        if (null !== $client && null === $loop) {
68
            throw new \RuntimeException(
69
                'You must give a LoopInterface instance with the Client'
70
            );
71
        }
72
73 108
        $this->loop = $loop ?: ReactFactory::buildEventLoop();
74 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...
75
76 108
        $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find();
77 108
        $this->streamFactory = $streamFactory ?: StreamFactoryDiscovery::find();
78 108
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 53
    public function sendRequest(RequestInterface $request)
84
    {
85 53
        $promise = $this->sendAsyncRequest($request);
86
87 53
        return $promise->wait();
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93 108
    public function sendAsyncRequest(RequestInterface $request)
94
    {
95 108
        $reactRequest = $this->buildReactRequest($request);
96 108
        $deferred = new Deferred();
97
98
        $reactRequest->on('error', function (\Exception $error) use ($deferred, $request) {
99 3
            $deferred->reject(new RequestException(
100 3
                $error->getMessage(),
101 3
                $request,
102
                $error
103 3
            ));
104 108
        });
105
106
        $reactRequest->on('response', function (ReactResponse $reactResponse = null) use ($deferred, $reactRequest, $request) {
107 105
            $bodyStream = $this->streamFactory->createStream();
108
            $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...
109 105
                if ($data instanceof StreamInterface) {
110 105
                    $bodyStream->write($data->getContents());
111 105
                } else {
112
                    $bodyStream->write($data);
113
                }
114 105
            });
115
116 105
            $reactResponse->on('end', function (\Exception $error = null) use ($deferred, $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...
117 105
                $response = $this->buildResponse(
118 105
                    $reactResponse,
0 ignored issues
show
Bug introduced by
It seems like $reactResponse defined by parameter $reactResponse on line 106 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...
119
                    $bodyStream
120 105
                );
121 105
                if (null !== $error) {
122
                    $deferred->reject(new HttpException(
123
                        $error->getMessage(),
124
                        $request,
125
                        $response,
126
                        $error
127
                    ));
128
                } else {
129 105
                    $deferred->resolve($response);
130
                }
131 105
            });
132 108
        });
133
134 108
        $reactRequest->end((string) $request->getBody());
135
136 108
        $promise = new Promise($deferred->promise());
137 108
        $promise->setLoop($this->loop);
138
139 108
        return $promise;
140
    }
141
142
    /**
143
     * Build a React request from the PSR7 RequestInterface.
144
     *
145
     * @param RequestInterface $request
146
     *
147
     * @return ReactRequest
148
     */
149 108
    private function buildReactRequest(RequestInterface $request)
150
    {
151 108
        $headers = [];
152
153 108
        foreach ($request->getHeaders() as $name => $value) {
154 108
            $headers[$name] = (is_array($value) ? $value[0] : $value);
155 108
        }
156
157 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...
158 108
            $request->getMethod(),
159 108
            (string) $request->getUri(),
160 108
            $headers,
161 108
            $request->getProtocolVersion()
162 108
        );
163
164 108
        return $reactRequest;
165
    }
166
167
    /**
168
     * Transform a React Response to a valid PSR7 ResponseInterface instance.
169
     *
170
     * @param ReactResponse $response
171
     * @param StreamInterface $body
172
     *
173
     * @return ResponseInterface
174
     */
175 105
    private function buildResponse(
176
        ReactResponse $response,
177
        StreamInterface $body
178
    ) {
179 105
        $body->rewind();
180
181 105
        return $this->responseFactory->createResponse(
182 105
            $response->getCode(),
183 105
            $response->getReasonPhrase(),
184 105
            $response->getHeaders(),
185 105
            $body,
186 105
            $response->getVersion()
187 105
        );
188
    }
189
}
190