basic async-interop support; generator consumer missing
[m6w6/seekat] / lib / API / Call.php
1 <?php
2
3 namespace seekat\API;
4
5 use AsyncInterop\Promise;
6 use http\Url;
7 use seekat\API;
8 use seekat\Exception;
9
10 final class Call
11 {
12 /**
13 * @var API
14 */
15 private $api;
16
17 /**
18 * @var string
19 */
20 private $call;
21
22 function __construct(API $api, string $call) {
23 $this->api = $api;
24 $this->call = $call;
25 }
26
27 function __invoke(array $args) : Promise {
28 $promise = $this->api->{$this->call}->get(...$args);
29
30 /* fetch resource, unless already localized, and try for {$method}_url */
31 if (!$this->api->exists($this->call)) {
32 $promise->when(function($error, $value) use($args) {
33 if (!isset($error)) {
34 return $value;
35 }
36 if ($this->api->exists($this->call."_url", $url)) {
37 $url = new Url(uri_template($url, (array)current($args)));
38 return $this->api->withUrl($url)->get(...$args);
39 }
40
41 $message = Exception\message($error);
42 $this->api->getLogger()->error("call($this->call): " . $message, [
43 "url" => (string) $this->api->getUrl()
44 ]);
45
46 throw $error;
47 });
48 }
49
50 return $promise;
51 }
52 }