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