drop async-interop
[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 $data = $this->checkResponseBody($response, $type);
28
29 return $this->api = $this->api->with(compact("type", "data", "links"));
30 }
31
32 /**
33 * @param Response $response
34 * @return null|API\Links
35 * @throws RequestException
36 */
37 private function checkResponseMeta(Response $response) {
38 if ($response->getResponseCode() >= 400) {
39 $e = new RequestException($response);
40
41 $this->api->getLogger()->critical("response -> error: ".$e->getMessage(), [
42 "url" => (string) $this->api->getUrl(),
43 ]);
44
45 throw $e;
46 }
47
48 if (!($link = $response->getHeader("Link", Header::class))) {
49 $link = null;
50 }
51
52 return new API\Links($link);
53 }
54
55 private function checkResponseType(Response $response) {
56 if (!($type = $response->getHeader("Content-Type", Header::class))) {
57 $e = new RequestException($response);
58
59 $this->api->getLogger()->error("response -> error: Empty Content-Type -> ".$e->getMessage(), [
60 "url" => (string) $this->api->getUrl(),
61 ]);
62
63 throw $e;
64 }
65
66 return new API\ContentType($type);
67 }
68
69 private function checkResponseBody(Response $response, API\ContentType $type) {
70 try {
71 $data = $type->parseBody($response->getBody());
72 } catch (\Exception $e) {
73 $this->api->getLogger()->error("response -> error: ".$e->getMessage(), [
74 "url" => (string) $this->api->getUrl(),
75 ]);
76
77 throw $e;
78 }
79
80 return $data;
81 }
82 }