3 namespace seekat\API\Call
;
5 use AsyncInterop\Promise
;
7 Client
, Client\Request
, Client\Response
9 use Psr\Log\LoggerInterface
;
15 * The response importer
36 * @var LoggerInterface
41 * The executed request
48 * The promised response
75 * Create a deferred promise for the response of $request
77 * @param API $api The endpoint of the request
78 * @param Request $request The request to execute
79 * @param Cache\Service $cache
81 function __construct(API
$api, Request
$request, Cache\Service
$cache = null) {
82 $this->request
= $request;
83 $this->client
= $api->getClient();
84 $this->logger
= $api->getLogger();
85 $this->result
= new Result($api);
86 $this->cache
= new Cache($cache);
88 $future = $api->getFuture();
89 $context = $future->createContext(function() {
90 if ($this->response
) {
91 /* we did finish in the meantime */
94 $this->client
->dequeue($this->request
);
95 ($this->reject
)("Cancelled");
98 $this->promise
= $future->getPromise($context);
99 $this->resolve
= API\Future\resolver
($future, $context);
100 $this->reject
= API\Future\rejecter
($future, $context);
103 function __invoke() : Promise
{
104 if ($this->cache
->load($this->request
, $cached)) {
105 $this->logger
->info("deferred -> cached", [
106 "method" => $this->request
->getRequestMethod(),
107 "url" => $this->request
->getRequestUrl(),
110 $this->response
= $cached;
113 $this->client
->enqueue($this->request
, function(Response
$response) use($cached) {
114 if ($response->getResponseCode() == 304) {
115 $this->response
= $cached;
117 $this->response
= $response;
122 $this->logger
->info("deferred -> enqueued", [
123 "method" => $this->request
->getRequestMethod(),
124 "url" => $this->request
->getRequestUrl(),
127 $this->client
->once();
130 return $this->promise
;
134 * Completion callback
136 private function complete() {
137 if ($this->response
) {
139 $api = ($this->result
)($this->response
);
141 $this->cache
->save($this->request
, $this->response
);
143 ($this->resolve
)($api);
144 } catch (\Throwable
$e) {
148 ($this->reject
)($this->client
->getTransferInfo($this->request
)->error
);