basic async-interop support; generator consumer missing
[m6w6/seekat] / lib / API / Call / Result.php
1 <?php
2
3 namespace seekat\API\Call;
4
5 use http\Client\Response;
6 use http\Header;
7 use seekat\API;
8 use seekat\Exception\RequestException;
9
10 final class Result
11 {
12 private $api;
13
14 function __construct(API $api) {
15 $this->api = $api;
16 }
17
18 function __invoke(Response $response) : API {
19 $hit = $response->getHeader("X-Cache-Time") ? "cached" : "enqueued";
20 $this->api->getLogger()->info("$hit -> response", [
21 "url" => (string) $this->api->getUrl(),
22 "info" => $response->getInfo(),
23 ]);
24
25 $links = $this->checkResponseMeta($response);
26 $type = $this->checkResponseType($response);
27
28 try {
29 $data = $type->parseBody($response->getBody());
30 } catch (\Exception $e) {
31 $this->api->getLogger()->error("response -> error: ".$e->getMessage(), [
32 "url" => (string) $this->api->getUrl(),
33 ]);
34
35 throw $e;
36 }
37
38 return $this->api = $this->api->with(compact("type", "data", "links"));
39 }
40
41 /**
42 * @param Response $response
43 * @return null|API\Links
44 * @throws RequestException
45 */
46 private function checkResponseMeta(Response $response) {
47 if ($response->getResponseCode() >= 400) {
48 $e = new RequestException($response);
49
50 $this->api->getLogger()->critical("response -> error: ".$e->getMessage(), [
51 "url" => (string) $this->api->getUrl(),
52 ]);
53
54 throw $e;
55 }
56
57 if (!($link = $response->getHeader("Link", Header::class))) {
58 $link = null;
59 }
60
61 return new API\Links($link);
62 }
63
64 private function checkResponseType(Response $response) {
65 if (!($type = $response->getHeader("Content-Type", Header::class))) {
66 $e = new RequestException($response);
67
68 $this->api->getLogger()->error("response -> error: Empty Content-Type -> ".$e->getMessage(), [
69 "url" => (string) $this->api->getUrl(),
70 ]);
71
72 throw $e;
73 }
74
75 return new API\ContentType($type);
76 }
77 }