|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is a part of the DiscordPHP-Http project. |
| 5 | + * |
| 6 | + * Copyright (c) 2021-present David Cole <david.cole1340@gmail.com> |
| 7 | + * |
| 8 | + * This file is subject to the MIT license that is bundled |
| 9 | + * with this source code in the LICENSE file. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Discord\Http\Drivers; |
| 13 | + |
| 14 | +use Discord\Http\DriverInterface; |
| 15 | +use Discord\Http\Request; |
| 16 | +use GuzzleHttp\Client; |
| 17 | +use GuzzleHttp\RequestOptions; |
| 18 | +use React\EventLoop\LoopInterface; |
| 19 | +use React\Promise\Deferred; |
| 20 | +use React\Promise\ExtendedPromiseInterface; |
| 21 | + |
| 22 | +/** |
| 23 | + * guzzlehttp/guzzle driver for Discord HTTP client. (still with React Promise) |
| 24 | + * |
| 25 | + * @author SQKo |
| 26 | + */ |
| 27 | +class Guzzle implements DriverInterface |
| 28 | +{ |
| 29 | + /** |
| 30 | + * ReactPHP event loop. |
| 31 | + * |
| 32 | + * @var LoopInterface|null |
| 33 | + */ |
| 34 | + protected $loop; |
| 35 | + |
| 36 | + /** |
| 37 | + * GuzzleHTTP/Guzzle client. |
| 38 | + * |
| 39 | + * @var Client |
| 40 | + */ |
| 41 | + protected $client; |
| 42 | + |
| 43 | + /** |
| 44 | + * Constructs the Guzzle driver. |
| 45 | + * |
| 46 | + * @param LoopInterface|null $loop |
| 47 | + * @param array $options |
| 48 | + */ |
| 49 | + public function __construct(?LoopInterface $loop = null, array $options = []) |
| 50 | + { |
| 51 | + $this->loop = $loop; |
| 52 | + |
| 53 | + // Allow 400 and 500 HTTP requests to be resolved rather than rejected. |
| 54 | + $options['http_errors'] = false; |
| 55 | + $this->client = new Client($options); |
| 56 | + } |
| 57 | + |
| 58 | + public function runRequest(Request $request): ExtendedPromiseInterface |
| 59 | + { |
| 60 | + // Create a React promise |
| 61 | + $deferred = new Deferred(); |
| 62 | + $reactPromise = $deferred->promise(); |
| 63 | + |
| 64 | + $promise = $this->client->requestAsync($request->getMethod(), $request->getUrl(), [ |
| 65 | + RequestOptions::HEADERS => $request->getHeaders(), |
| 66 | + RequestOptions::BODY => $request->getContent(), |
| 67 | + ])->then([$deferred, 'resolve'], [$deferred, 'reject']); |
| 68 | + |
| 69 | + if ($this->loop) { |
| 70 | + $this->loop->futureTick([$promise, 'wait']); |
| 71 | + } else { |
| 72 | + $promise->wait(); |
| 73 | + } |
| 74 | + |
| 75 | + return $reactPromise; |
| 76 | + } |
| 77 | +} |
0 commit comments