PHP8
[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 * @param Response $response
40 * @return null|API\Links
41 * @throws RequestException
42 */
43 private function checkResponseMeta(Response $response) {
44 if ($response->getResponseCode() >= 400) {
45 $e = new RequestException($response);
46
47 $this->api->getLogger()->critical("response -> error: ".$e->getMessage(), [
48 "url" => (string) $this->api->getUrl(),
49 ]);
50
51 throw $e;
52 }
53
54 if (!($link = $response->getHeader("Link", Header::class))) {
55 $link = null;
56 }
57
58 return new API\Links($link);
59 }
60
61 /**
62 * @param Response $response
63 * @return API\ContentType
64 * @throws RequestException
65 */
66 private function checkResponseType(Response $response) {
67 if (!($type = $response->getHeader("Content-Type", Header::class))) {
68 $e = new RequestException($response);
69
70 $this->api->getLogger()->error("response -> error: Empty Content-Type -> ".$e->getMessage(), [
71 "url" => (string) $this->api->getUrl(),
72 ]);
73
74 throw $e;
75 }
76
77 return new API\ContentType($this->api->getVersion(), $type->value);
78 }
79
80 /**
81 * @param Response $response
82 * @param API\ContentType $type
83 * @return mixed
84 * @throws \Exception
85 */
86 private function checkResponseBody(Response $response, API\ContentType $type) {
87 try {
88 $data = $type->decode($response->getBody());
89 } catch (\Exception $e) {
90 $this->api->getLogger()->error("response -> error: ".$e->getMessage(), [
91 "url" => (string) $this->api->getUrl(),
92 ]);
93
94 throw $e;
95 }
96
97 return $data;
98 }
99 }