Completed
Push — master ( a6feea...7247a2 )
by Stéphane
06:46
created

Client::buildResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4286
cc 1
eloc 10
nc 1
nop 2
1
<?php
2
3
namespace Http\Adapter\React;
4
5
use React\EventLoop\LoopInterface;
6
use React\Promise\Deferred;
7
use React\HttpClient\Client as ReactClient;
8
use React\HttpClient\Request as ReactRequest;
9
use React\HttpClient\Response as ReactResponse;
10
use Http\Client\HttpClient;
11
use Http\Client\HttpAsyncClient;
12
use Http\Client\Exception\HttpException;
13
use Http\Client\Exception\RequestException;
14
use Http\Promise\Promise;
15
use Http\Message\MessageFactory;
16
use Psr\Http\Message\RequestInterface;
17
use Psr\Http\Message\StreamInterface;
18
19
/**
20
 * Client for the React promise implementation
21
 * @author Stéphane Hulard <[email protected]>
22
 */
23
class Client implements HttpClient, HttpAsyncClient
24
{
25
    /**
26
     * React HTTP client
27
     * @var Client
28
     */
29
    private $client;
30
31
    /**
32
     * React event loop
33
     * @var LoopInterface
34
     */
35
    private $loop;
36
37
    /**
38
     * HttpPlug message factory
39
     * @var MessageFactory
40
     */
41
    private $messageFactory;
42
43
    /**
44
     * Initialize the React client
45
     * @param LoopInterface|null $loop     React Event loop
46
     * @param Resolver           $resolver React async DNS resolver
0 ignored issues
show
Bug introduced by
There is no parameter named $resolver. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
47
     * @param ReactClient        $client   React client to use
48
     */
49
    public function __construct(
50
        MessageFactory $messageFactory,
51
        LoopInterface $loop = null,
52
        ReactClient $client = null
53
    ) {
54
        $this->loop = null === $loop?ReactFactory::buildEventLoop():$loop;
55
        if (null === $client) {
56
            $this->client = ReactFactory::buildHttpClient($this->loop);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Http\Adapter\React\Reac...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...
57
        } elseif (null === $loop) {
58
            throw new \RuntimeException(
59
                "You must give a LoopInterface instance with the Client"
60
            );
61
        }
62
63
        $this->messageFactory = $messageFactory;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function sendRequest(RequestInterface $request)
70
    {
71
        $promise = $this->sendAsyncRequest($request);
72
73
        return $promise->wait();
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function sendAsyncRequest(RequestInterface $request)
80
    {
81
        $requestStream = $this->buildReactRequest($request);
82
        $deferred = new Deferred();
83
84
        $requestStream->on('error', function (\Exception $error) use ($deferred, $request) {
85
            $deferred->reject(new RequestException(
86
                $error->getMessage(),
87
                $request,
88
                $error
89
            ));
90
        });
91
        $requestStream->on('response', function (ReactResponse $response = null) use ($deferred, $requestStream, $request) {
92
            $bodyStream = null;
93
            $response->on('data', function ($data) use (&$bodyStream) {
0 ignored issues
show
Bug introduced by
It seems like $response 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...
94
                if ($data instanceof StreamInterface) {
95
                    $bodyStream = $data;
96
                } else {
97
                    $bodyStream->write($data);
0 ignored issues
show
Bug introduced by
The method write cannot be called on $bodyStream (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
98
                }
99
            });
100
101
            $response->on('end', function (\Exception $error = null) use ($deferred, $request, $response, &$bodyStream) {
0 ignored issues
show
Bug introduced by
It seems like $response 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...
102
                $bodyStream->rewind();
0 ignored issues
show
Bug introduced by
The method rewind cannot be called on $bodyStream (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
103
                $psr7Response = $this->buildResponse(
104
                    $response,
0 ignored issues
show
Bug introduced by
It seems like $response defined by parameter $response on line 91 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...
105
                    $bodyStream
0 ignored issues
show
Documentation introduced by
$bodyStream is of type null, but the function expects a object<Psr\Http\Message\StreamInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
106
                );
107
                if (null !== $error) {
108
                    $deferred->reject(new HttpException(
109
                        $error->getMessage(),
110
                        $request,
111
                        $psr7Response,
112
                        $error
113
                    ));
114
                } else {
115
                    $deferred->resolve($psr7Response);
116
                }
117
            });
118
        });
119
120
        $requestStream->end((string)$request->getBody());
121
122
        $promise = new ReactPromiseAdapter($deferred->promise());
123
        $promise->setLoop($this->loop);
124
        return $promise;
125
    }
126
127
    /**
128
     * Build a React request from the PSR7 RequestInterface
129
     * @param  RequestInterface $request
130
     * @return ReactRequest
131
     */
132
    private function buildReactRequest(RequestInterface $request)
133
    {
134
        $headers = [];
135
        foreach ($request->getHeaders() as $name => $value) {
136
            $headers[$name] = (is_array($value)?$value[0]:$value);
137
        }
138
        if ($request->getBody()->getSize() > 0) {
139
            $headers['Content-Length'] = $request->getBody()->getSize();
140
        }
141
142
        $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...
143
            $request->getMethod(),
144
            (string)$request->getUri(),
145
            $headers,
146
            $request->getProtocolVersion()
147
        );
148
149
        return $reactRequest;
150
    }
151
152
    /**
153
     * Transform a React Response to a valid PSR7 ResponseInterface instance
154
     * @param  ReactResponse $response
155
     * @return ResponseInterface
156
     */
157
    private function buildResponse(
158
        ReactResponse $response,
159
        StreamInterface $body
160
    ) {
161
        $body->rewind();
162
        return $this->messageFactory->createResponse(
163
            $response->getCode(),
164
            $response->getReasonPhrase(),
165
            $response->getHeaders(),
166
            $body,
167
            $response->getVersion()
168
        );
169
    }
170
}
171