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