Completed
Push — master ( 412356...c961c9 )
by Stéphane
18s queued 12s
created

Client::sendAsyncRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.064

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 9
c 2
b 0
f 0
dl 0
loc 14
ccs 3
cts 5
cp 0.6
rs 9.9666
cc 1
nc 1
nop 1
crap 1.064
1
<?php
2
3
namespace Http\Adapter\React;
4
5
use Http\Client\HttpClient;
6
use Http\Client\HttpAsyncClient;
7
use Psr\Http\Message\RequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use React\EventLoop\LoopInterface;
10
use React\Http\Browser as ReactBrowser;
11
12
/**
13
 * Client for the React promise implementation.
14
 *
15
 * @author Stéphane Hulard <[email protected]>
16
 */
17
class Client implements HttpClient, HttpAsyncClient
18
{
19
    /**
20
     * React HTTP client.
21
     *
22
     * @var ReactBrowser
23
     */
24
    private $client;
25
26
    /**
27
     * React event loop.
28
     *
29
     * @var LoopInterface
30
     */
31
    private $loop;
32
33
    /**
34
     * Initialize the React client.
35
     */
36
    public function __construct(
37
        LoopInterface $loop = null,
38
        ReactBrowser $client = null
39
    ) {
40
        if (null !== $client && null === $loop) {
41
            throw new \RuntimeException('You must give a LoopInterface instance with the Client');
42
        }
43
44
        $this->loop = $loop ?: ReactFactory::buildEventLoop();
45
        $this->client = $client ?: ReactFactory::buildHttpClient($this->loop);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function sendRequest(RequestInterface $request): ResponseInterface
52
    {
53
        $promise = $this->sendAsyncRequest($request);
54
55
        return $promise->wait();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $promise->wait() could return the type null which is incompatible with the type-hinted return Psr\Http\Message\ResponseInterface. Consider adding an additional type-check to rule them out.
Loading history...
56
    }
57
58
    /**
59
     * {@inheritdoc}
60 104
     */
61
    public function sendAsyncRequest(RequestInterface $request)
62
    {
63
        $promise = new Promise(
64
            $this->client->request(
65
                $request->getMethod(),
66 104
                $request->getUri(),
67
                $request->getHeaders(),
68
                $request->getBody()
69
            ),
70
            $this->loop,
71
            $request
72 104
        );
73 104
74
        return $promise;
75 104
    }
76
}
77