Completed
Pull Request — master (#23)
by Joel
05:03
created

Client::sendRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
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\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
        $promise = new Promise($this->loop);
97
98
        $reactRequest->on('error', function (\Exception $error) use ($promise, $request) {
99 3
            $promise->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 ($promise, $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
                $bodyStream->write((string) $data);
110 105
            });
111
112 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...
113 105
                $response = $this->buildResponse(
114 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...
115
                    $bodyStream
116 105
                );
117 105
                if (null !== $error) {
118
                    $promise->reject(new HttpException(
119
                        $error->getMessage(),
120
                        $request,
121
                        $response,
122
                        $error
123
                    ));
124
                } else {
125 105
                    $promise->resolve($response);
126
                }
127 105
            });
128 108
        });
129
130 108
        $reactRequest->end((string) $request->getBody());
131
132 108
        return $promise;
133
    }
134
135
    /**
136
     * Build a React request from the PSR7 RequestInterface.
137
     *
138
     * @param RequestInterface $request
139
     *
140
     * @return ReactRequest
141
     */
142 108
    private function buildReactRequest(RequestInterface $request)
143
    {
144 108
        $headers = [];
145
146 108
        foreach ($request->getHeaders() as $name => $value) {
147 108
            $headers[$name] = (is_array($value) ? $value[0] : $value);
148 108
        }
149
150 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...
151 108
            $request->getMethod(),
152 108
            (string) $request->getUri(),
153 108
            $headers,
154 108
            $request->getProtocolVersion()
155 108
        );
156
157 108
        return $reactRequest;
158
    }
159
160
    /**
161
     * Transform a React Response to a valid PSR7 ResponseInterface instance.
162
     *
163
     * @param ReactResponse   $response
164
     * @param StreamInterface $body
165
     *
166
     * @return ResponseInterface
167
     */
168 105
    private function buildResponse(
169
        ReactResponse $response,
170
        StreamInterface $body
171
    ) {
172 105
        $body->rewind();
173
174 105
        return $this->responseFactory->createResponse(
175 105
            $response->getCode(),
176 105
            $response->getReasonPhrase(),
177 105
            $response->getHeaders(),
178 105
            $body,
179 105
            $response->getVersion()
180 105
        );
181
    }
182
}
183