Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

88 linhas
2.2 KiB

  1. <?php
  2. namespace GuzzleHttp\Promise;
  3. /**
  4. * A promise that has been rejected.
  5. *
  6. * Thenning off of this promise will invoke the onRejected callback
  7. * immediately and ignore other callbacks.
  8. */
  9. class RejectedPromise implements PromiseInterface
  10. {
  11. private $reason;
  12. public function __construct($reason)
  13. {
  14. if (method_exists($reason, 'then')) {
  15. throw new \InvalidArgumentException(
  16. 'You cannot create a RejectedPromise with a promise.');
  17. }
  18. $this->reason = $reason;
  19. }
  20. public function then(
  21. callable $onFulfilled = null,
  22. callable $onRejected = null
  23. ) {
  24. // If there's no onRejected callback then just return self.
  25. if (!$onRejected) {
  26. return $this;
  27. }
  28. $queue = queue();
  29. $reason = $this->reason;
  30. $p = new Promise([$queue, 'run']);
  31. $queue->add(static function () use ($p, $reason, $onRejected) {
  32. if ($p->getState() === self::PENDING) {
  33. try {
  34. // Return a resolved promise if onRejected does not throw.
  35. $p->resolve($onRejected($reason));
  36. } catch (\Throwable $e) {
  37. // onRejected threw, so return a rejected promise.
  38. $p->reject($e);
  39. } catch (\Exception $e) {
  40. // onRejected threw, so return a rejected promise.
  41. $p->reject($e);
  42. }
  43. }
  44. });
  45. return $p;
  46. }
  47. public function otherwise(callable $onRejected)
  48. {
  49. return $this->then(null, $onRejected);
  50. }
  51. public function wait($unwrap = true, $defaultDelivery = null)
  52. {
  53. if ($unwrap) {
  54. throw exception_for($this->reason);
  55. }
  56. }
  57. public function getState()
  58. {
  59. return self::REJECTED;
  60. }
  61. public function resolve($value)
  62. {
  63. throw new \LogicException("Cannot resolve a rejected promise");
  64. }
  65. public function reject($reason)
  66. {
  67. if ($reason !== $this->reason) {
  68. throw new \LogicException("Cannot reject a rejected promise");
  69. }
  70. }
  71. public function cancel()
  72. {
  73. // pass
  74. }
  75. }