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