Guzzle.php 1.9 KB

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