1 | <?php |
||
2 | |||
3 | namespace Http\Adapter\React; |
||
4 | |||
5 | use Http\Client\HttpAsyncClient; |
||
6 | use Http\Client\HttpClient; |
||
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 | 104 | public function __construct( |
|
37 | LoopInterface $loop = null, |
||
38 | ReactBrowser $client = null |
||
39 | ) { |
||
40 | 104 | if (null !== $client && null === $loop) { |
|
41 | throw new \RuntimeException('You must give a LoopInterface instance with the Client'); |
||
42 | } |
||
43 | |||
44 | 104 | $this->loop = $loop ?: ReactFactory::buildEventLoop(); |
|
45 | 104 | $this->client = $client ?: ReactFactory::buildHttpClient($this->loop); |
|
46 | 104 | } |
|
47 | |||
48 | /** |
||
49 | * {@inheritdoc} |
||
50 | */ |
||
51 | 51 | public function sendRequest(RequestInterface $request): ResponseInterface |
|
52 | { |
||
53 | 51 | $promise = $this->sendAsyncRequest($request); |
|
54 | |||
55 | 51 | return $promise->wait(); |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
56 | } |
||
57 | |||
58 | /** |
||
59 | * {@inheritdoc} |
||
60 | */ |
||
61 | 104 | public function sendAsyncRequest(RequestInterface $request) |
|
62 | { |
||
63 | 104 | $promise = new Promise( |
|
64 | 104 | $this->client->request( |
|
65 | 104 | $request->getMethod(), |
|
66 | 104 | $request->getUri(), |
|
67 | 104 | $request->getHeaders(), |
|
68 | 104 | $request->getBody() |
|
69 | ), |
||
70 | 104 | $this->loop, |
|
71 | 104 | $request |
|
72 | ); |
||
73 | |||
74 | 104 | return $promise; |
|
75 | } |
||
76 | } |
||
77 |