Completed
Push — master ( 7247a2...0efe74 )
by Stéphane
06:34
created

Client::__construct()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 15
rs 8.8571
cc 5
eloc 10
nc 5
nop 3
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\Message\MessageFactory;
15
use Psr\Http\Message\RequestInterface;
16
use Psr\Http\Message\StreamInterface;
17
18
/**
19
 * Client for the React promise implementation.
20
 *
21
 * @author Stéphane Hulard <[email protected]>
22
 */
23
class Client implements HttpClient, HttpAsyncClient
24
{
25
    /**
26
     * React HTTP client.
27
     *
28
     * @var Client
29
     */
30
    private $client;
31
32
    /**
33
     * React event loop.
34
     *
35
     * @var LoopInterface
36
     */
37
    private $loop;
38
39
    /**
40
     * HttpPlug message factory.
41
     *
42
     * @var MessageFactory
43
     */
44
    private $messageFactory;
45
46
    /**
47
     * Initialize the React client.
48
     *
49
     * @param LoopInterface|null $loop     React Event loop
50
     * @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...
51
     * @param ReactClient        $client   React client to use
52
     */
53
    public function __construct(
54
        MessageFactory $messageFactory,
55
        LoopInterface $loop = null,
56
        ReactClient $client = null
57
    ) {
58
        if (null !== $client && null === $loop) {
59
            throw new \RuntimeException(
60
                'You must give a LoopInterface instance with the Client'
61
            );
62
        }
63
        $this->loop = (null !== $loop) ?: ReactFactory::buildEventLoop();
0 ignored issues
show
Documentation Bug introduced by
It seems like null !== $loop ?: \Http\...ctory::buildEventLoop() can also be of type boolean. However, the property $loop is declared as type object<React\EventLoop\LoopInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
64
        $this->client = (null !== $client) ?: ReactFactory::buildHttpClient($this->loop);
0 ignored issues
show
Bug introduced by
It seems like $this->loop can also be of type boolean; however, Http\Adapter\React\ReactFactory::buildHttpClient() does only seem to accept object<React\EventLoop\LoopInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Documentation Bug introduced by
It seems like null !== $client ?: \Htt...HttpClient($this->loop) of type boolean or 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...
65
66
        $this->messageFactory = $messageFactory;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function sendRequest(RequestInterface $request)
73
    {
74
        $promise = $this->sendAsyncRequest($request);
75
76
        return $promise->wait();
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function sendAsyncRequest(RequestInterface $request)
83
    {
84
        $reactRequest = $this->buildReactRequest($request);
85
        $deferred = new Deferred();
86
87
        $reactRequest->on('error', function (\Exception $error) use ($deferred, $request) {
88
            $deferred->reject(new RequestException(
89
                $error->getMessage(),
90
                $request,
91
                $error
92
            ));
93
        });
94
        $reactRequest->on('response', function (ReactResponse $reactResponse = null) use ($deferred, $reactRequest, $request) {
95
            $bodyStream = null;
96
            $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...
97
                if ($data instanceof StreamInterface) {
98
                    $bodyStream = $data;
99
                } else {
100
                    $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...
101
                }
102
            });
103
104
            $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...
105
                $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...
106
                $response = $this->buildResponse(
107
                    $reactResponse,
0 ignored issues
show
Bug introduced by
It seems like $reactResponse defined by parameter $reactResponse on line 94 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...
108
                    $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...
109
                );
110
                if (null !== $error) {
111
                    $deferred->reject(new HttpException(
112
                        $error->getMessage(),
113
                        $request,
114
                        $response,
115
                        $error
116
                    ));
117
                } else {
118
                    $deferred->resolve($response);
119
                }
120
            });
121
        });
122
123
        $reactRequest->end((string) $request->getBody());
124
125
        $promise = new Promise($deferred->promise());
126
        $promise->setLoop($this->loop);
127
128
        return $promise;
129
    }
130
131
    /**
132
     * Build a React request from the PSR7 RequestInterface.
133
     *
134
     * @param RequestInterface $request
135
     *
136
     * @return ReactRequest
137
     */
138
    private function buildReactRequest(RequestInterface $request)
139
    {
140
        $headers = [];
141
        foreach ($request->getHeaders() as $name => $value) {
142
            $headers[$name] = (is_array($value) ? $value[0] : $value);
143
        }
144
145
        $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...
146
            $request->getMethod(),
147
            (string) $request->getUri(),
148
            $headers,
149
            $request->getProtocolVersion()
150
        );
151
152
        return $reactRequest;
153
    }
154
155
    /**
156
     * Transform a React Response to a valid PSR7 ResponseInterface instance.
157
     *
158
     * @param ReactResponse $response
159
     *
160
     * @return ResponseInterface
161
     */
162
    private function buildResponse(
163
        ReactResponse $response,
164
        StreamInterface $body
165
    ) {
166
        $body->rewind();
167
168
        return $this->messageFactory->createResponse(
169
            $response->getCode(),
170
            $response->getReasonPhrase(),
171
            $response->getHeaders(),
172
            $body,
173
            $response->getVersion()
174
        );
175
    }
176
}
177