HttplugPromise.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpClient\Response;
  11. use function GuzzleHttp\Promise\promise_for;
  12. use GuzzleHttp\Promise\PromiseInterface as GuzzlePromiseInterface;
  13. use Http\Promise\Promise as HttplugPromiseInterface;
  14. use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
  15. /**
  16. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  17. *
  18. * @internal
  19. */
  20. final class HttplugPromise implements HttplugPromiseInterface
  21. {
  22. private $promise;
  23. public function __construct(GuzzlePromiseInterface $promise)
  24. {
  25. $this->promise = $promise;
  26. }
  27. public function then(callable $onFulfilled = null, callable $onRejected = null): self
  28. {
  29. return new self($this->promise->then(
  30. $this->wrapThenCallback($onFulfilled),
  31. $this->wrapThenCallback($onRejected)
  32. ));
  33. }
  34. public function cancel(): void
  35. {
  36. $this->promise->cancel();
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function getState(): string
  42. {
  43. return $this->promise->getState();
  44. }
  45. /**
  46. * {@inheritdoc}
  47. *
  48. * @return Psr7ResponseInterface|mixed
  49. */
  50. public function wait($unwrap = true)
  51. {
  52. $result = $this->promise->wait($unwrap);
  53. while ($result instanceof HttplugPromiseInterface || $result instanceof GuzzlePromiseInterface) {
  54. $result = $result->wait($unwrap);
  55. }
  56. return $result;
  57. }
  58. private function wrapThenCallback(?callable $callback): ?callable
  59. {
  60. if (null === $callback) {
  61. return null;
  62. }
  63. return static function ($value) use ($callback) {
  64. return promise_for($callback($value));
  65. };
  66. }
  67. }