9bdc030ba955e07c562b20f6913c8d88b6c62287
3 namespace seekat\API\Call
;
5 use AsyncInterop\Promise
;
8 Client
, Client\Request
, Client\Response
10 use Psr\Log\LoggerInterface
;
15 final class Deferred
implements SplObserver
18 * The response importer
39 * @var LoggerInterface
44 * The executed request
51 * The promised response
78 * Create a deferred promise for the response of $request
80 * @param API $api The endpoint of the request
81 * @param Request $request The request to execute
82 * @param Cache\Service $cache
84 function __construct(API
$api, Request
$request, Cache\Service
$cache = null) {
85 $this->request
= $request;
86 $this->client
= $api->getClient();
87 $this->logger
= $api->getLogger();
88 $this->result
= new Result($api);
89 $this->cache
= new Cache($cache);
91 $future = $api->getFuture();
92 $context = $future->createContext(function() {
93 if ($this->response
) {
94 /* we did finish in the meantime */
97 $this->client
->detach($this);
98 $this->client
->dequeue($this->request
);
99 ($this->reject
)("Cancelled");
102 $this->promise
= $future->getPromise($context);
103 $this->resolve
= API\Future\resolver
($future, $context);
104 $this->reject
= API\Future\rejecter
($future, $context);
105 $this->update
= API\Future\
updater($future, $context);
108 function __invoke() : Promise
{
109 if ($this->cache
->load($this->request
, $cached)) {
110 $this->logger
->info("deferred -> cached", [
111 "method" => $this->request
->getRequestMethod(),
112 "url" => $this->request
->getRequestUrl(),
115 $this->response
= $cached;
118 $this->client
->attach($this);
119 $this->client
->enqueue($this->request
, function(Response
$response) use($cached) {
120 if ($response->getResponseCode() == 304) {
121 $this->response
= $cached;
123 $this->response
= $response;
128 $this->logger
->info("deferred -> enqueued", [
129 "method" => $this->request
->getRequestMethod(),
130 "url" => $this->request
->getRequestUrl(),
133 $this->client
->once();
136 return $this->promise
;
142 * Import the response's data on success and resolve the promise.
144 * @param SplSubject $client The observed HTTP client
145 * @param Request $request The request which generated the update
146 * @param object $progress The progress information
148 function update(SplSubject
$client, Request
$request = null, $progress = null) {
149 if ($request !== $this->request
) {
153 ($this->update
)((object) compact("client", "request", "progress"));
157 * Completion callback
158 * @param callable $resolve
159 * @param callable $reject
161 private function complete() {
162 $this->client
->detach($this);
164 if ($this->response
) {
166 $api = ($this->result
)($this->response
);
168 $this->cache
->save($this->request
, $this->response
);
170 ($this->resolve
)($api);
171 } catch (Exception
$e) {
175 ($this->reject
)($this->client
->getTransferInfo($this->request
)->error
);