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