React.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 React\EventLoop\LoopInterface;
  14. use React\Http\Browser;
  15. use React\Promise\ExtendedPromiseInterface;
  16. use React\Socket\Connector;
  17. /**
  18. * react/http driver for Discord HTTP client.
  19. *
  20. * @author David Cole <david.cole1340@gmail.com>
  21. */
  22. class React implements DriverInterface
  23. {
  24. /**
  25. * ReactPHP event loop.
  26. *
  27. * @var LoopInterface
  28. */
  29. protected $loop;
  30. /**
  31. * ReactPHP/HTTP browser.
  32. *
  33. * @var Browser
  34. */
  35. protected $browser;
  36. /**
  37. * Constructs the Guzzle driver.
  38. *
  39. * @param LoopInterface $loop
  40. * @param array $options
  41. */
  42. public function __construct(LoopInterface $loop, array $options = [])
  43. {
  44. $this->loop = $loop;
  45. // Allow 400 and 500 HTTP requests to be resolved rather than rejected.
  46. $browser = new Browser($loop, new Connector($loop, $options));
  47. $this->browser = $browser->withRejectErrorResponse(false);
  48. }
  49. public function runRequest(Request $request): ExtendedPromiseInterface
  50. {
  51. return $this->browser->{$request->getMethod()}(
  52. $request->getUrl(),
  53. $request->getHeaders(),
  54. $request->getContent()
  55. );
  56. }
  57. }