update to PHP-8.1
[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 private $api;
12
13 function __construct(API $api) {
14 $this->api = $api;
15 }
16
17 /**
18 * @param Response $response
19 * @return API
20 * @throws RequestException
21 */
22 function __invoke(Response $response) : API {
23 $links = $this->checkResponseMeta($response);
24 $type = $this->checkResponseType($response);
25 $data = $this->checkResponseBody($response, $type);
26
27 $this->api->getLogger()->info("response -> info", [
28 "type" => $type->getType(),
29 "links" => $links->getRelations(),
30 ]);
31 $this->api->getLogger()->debug("response -> data", [
32 "data" => $data,
33 ]);
34
35 return $this->api = $this->api->with(compact("type", "data", "links"));
36 }
37
38 /**
39 * @throws RequestException
40 */
41 private function checkResponseMeta(Response $response) : API\Links {
42 if ($response->getResponseCode() >= 400) {
43 $e = new RequestException($response);
44
45 $this->api->getLogger()->critical("response -> error: ".$e->getMessage(), [
46 "url" => (string) $this->api->getUrl(),
47 ]);
48
49 throw $e;
50 }
51
52 if (!($link = $response->getHeader("Link", Header::class))) {
53 $link = null;
54 }
55
56 return new API\Links($link);
57 }
58
59 /**
60 * @throws RequestException
61 */
62 private function checkResponseType(Response $response) : API\ContentType {
63 if (!($type = $response->getHeader("Content-Type", Header::class))) {
64 $e = new RequestException($response);
65
66 $this->api->getLogger()->error("response -> error: Empty Content-Type -> ".$e->getMessage(), [
67 "url" => (string) $this->api->getUrl(),
68 ]);
69
70 throw $e;
71 }
72
73 return new API\ContentType($this->api->getVersion(), $type->value);
74 }
75
76 /**
77 * @throws \Exception
78 */
79 private function checkResponseBody(Response $response, API\ContentType $type) : mixed {
80 try {
81 $data = $type->decode($response->getBody());
82 } catch (\Exception $e) {
83 $this->api->getLogger()->error("response -> error: ".$e->getMessage(), [
84 "url" => (string) $this->api->getUrl(),
85 ]);
86
87 throw $e;
88 }
89
90 return $data;
91 }
92 }