3 namespace seekat\API\Call
;
7 Client
, Client\Request
, Client\Response
13 final class Deferred
extends \React\Promise\Deferred
implements SplObserver
16 * The response importer
37 * The executed request
44 * The promised response
51 * Create a deferred promise for the response of $request
53 * @param API $api The endpoint of the request
54 * @param Request $request The request to execute
55 * @param Cache\Service $cache
57 function __construct(API
$api, Request
$request, Cache\Service
$cache = null) {
58 parent
::__construct(function ($resolve, $reject) {
59 return $this->cancel($resolve, $reject);
62 $this->request
= $request;
63 $this->client
= $api->getClient();
64 $this->result
= new Result($api);
65 $this->cache
= new Cache($cache);
67 if ($this->cache
->load($this->request
, $cached)) {
68 $api->getLogger()->info("deferred -> cached", [
69 "method" => $request->getRequestMethod(),
70 "url" => $request->getRequestUrl(),
73 $this->response
= $cached;
79 $this->client
->attach($this);
80 $this->client
->enqueue($this->request
, function(Response
$response) use($cached) {
81 if ($response->getResponseCode() == 304) {
82 $this->response
= $cached;
84 $this->response
= $response;
92 $api->getLogger()->info("deferred -> enqueued", [
93 "method" => $request->getRequestMethod(),
94 "url" => $request->getRequestUrl(),
97 $this->client
->once();
104 * Import the response's data on success and resolve the promise.
106 * @param SplSubject $client The observed HTTP client
107 * @param Request $request The request which generated the update
108 * @param object $progress The progress information
110 function update(SplSubject
$client, Request
$request = null, $progress = null) {
111 if ($request !== $this->request
) {
115 $this->notify((object) compact("client", "request", "progress"));
119 * Completion callback
120 * @param callable $resolve
121 * @param callable $reject
123 private function complete(callable
$resolve, callable
$reject) {
124 $this->client
->detach($this);
126 if ($this->response
) {
128 $api = ($this->result
)($this->response
);
130 $this->cache
->save($this->request
, $this->response
);
133 } catch (Exception
$e) {
137 $reject($this->client
->getTransferInfo($this->request
)->error
);
142 * Cancellation callback
143 * @param callable $resolve
144 * @param callable $reject
146 private function cancel(callable
$resolve, callable
$reject) {
147 /* did we finish in the meantime? */
148 if ($this->response
) {
149 $this->complete($resolve, $reject);
151 $this->client
->detach($this);
152 $this->client
->dequeue($this->request
);
153 $reject("Cancelled");