1 | <?php |
||
18 | final class Promise implements HttpPromise |
||
19 | { |
||
20 | /** |
||
21 | * @var PromiseInterface |
||
22 | */ |
||
23 | private $promise; |
||
24 | |||
25 | /** |
||
26 | * @var string State of the promise |
||
27 | */ |
||
28 | private $state; |
||
29 | |||
30 | /** |
||
31 | * @var ResponseInterface |
||
32 | */ |
||
33 | private $response; |
||
34 | |||
35 | /** |
||
36 | * @var HttplugException |
||
37 | */ |
||
38 | private $exception; |
||
39 | |||
40 | /** |
||
41 | * @var RequestInterface |
||
42 | */ |
||
43 | private $request; |
||
44 | |||
45 | /** |
||
46 | * @param PromiseInterface $promise |
||
47 | * @param RequestInterface $request |
||
48 | */ |
||
49 | 378 | public function __construct(PromiseInterface $promise, RequestInterface $request) |
|
50 | { |
||
51 | 378 | $this->request = $request; |
|
52 | 378 | $this->state = self::PENDING; |
|
53 | $this->promise = $promise->then(function ($response) { |
||
54 | 353 | $this->response = $response; |
|
55 | 353 | $this->state = self::FULFILLED; |
|
56 | |||
57 | 353 | return $response; |
|
58 | }, function ($reason) use ($request) { |
||
59 | 25 | $this->state = self::REJECTED; |
|
60 | |||
61 | 25 | if ($reason instanceof HttplugException) { |
|
62 | 6 | $this->exception = $reason; |
|
63 | 25 | } elseif ($reason instanceof GuzzleExceptions\GuzzleException) { |
|
64 | 21 | $this->exception = $this->handleException($reason, $request); |
|
65 | 4 | } elseif ($reason instanceof \Throwable) { |
|
66 | 3 | $this->exception = new HttplugException\TransferException('Invalid exception returned from Guzzle6', 0, $reason); |
|
67 | } else { |
||
68 | 1 | $this->exception = new UnexpectedValueException('Reason returned from Guzzle6 must be an Exception'); |
|
69 | } |
||
70 | |||
71 | 25 | throw $this->exception; |
|
72 | 378 | }); |
|
73 | 378 | } |
|
74 | |||
75 | /** |
||
76 | * {@inheritdoc} |
||
77 | */ |
||
78 | 159 | public function then(callable $onFulfilled = null, callable $onRejected = null) |
|
82 | |||
83 | /** |
||
84 | * {@inheritdoc} |
||
85 | */ |
||
86 | 369 | public function getState() |
|
90 | |||
91 | /** |
||
92 | * {@inheritdoc} |
||
93 | */ |
||
94 | 378 | public function wait($unwrap = true) |
|
106 | |||
107 | /** |
||
108 | * Converts a Guzzle exception into an Httplug exception. |
||
109 | * |
||
110 | * @param GuzzleExceptions\GuzzleException $exception |
||
111 | * @param RequestInterface $request |
||
112 | * |
||
113 | * @return HttplugException |
||
114 | */ |
||
115 | 21 | private function handleException(GuzzleExceptions\GuzzleException $exception, RequestInterface $request) |
|
141 | } |
||
142 |
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: