HttplugPromise.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 GuzzleHttp\Promise\Create;
  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. /**
  23. * @var GuzzlePromiseInterface
  24. */
  25. private $promise;
  26. /**
  27. * @param GuzzlePromiseInterface $promise
  28. */
  29. public function __construct($promise)
  30. {
  31. $this->promise = $promise;
  32. }
  33. public function then(callable $onFulfilled = null, callable $onRejected = null)
  34. {
  35. return new self($this->promise->then(
  36. $this->wrapThenCallback($onFulfilled),
  37. $this->wrapThenCallback($onRejected)
  38. ));
  39. }
  40. public function cancel()
  41. {
  42. $this->promise->cancel();
  43. }
  44. public function getState()
  45. {
  46. return $this->promise->getState();
  47. }
  48. /**
  49. * @return Psr7ResponseInterface|mixed
  50. */
  51. public function wait($unwrap = true)
  52. {
  53. $result = $this->promise->wait($unwrap);
  54. while ($result instanceof HttplugPromiseInterface || $result instanceof GuzzlePromiseInterface) {
  55. $result = $result->wait($unwrap);
  56. }
  57. return $result;
  58. }
  59. /**
  60. * @param callable|null $callback
  61. */
  62. private function wrapThenCallback($callback)
  63. {
  64. if (null === $callback) {
  65. return null;
  66. }
  67. return static function ($value) use ($callback) {
  68. return Create::promiseFor($callback($value));
  69. };
  70. }
  71. }