refactor
[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 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 $url = $this->api->getUrl();
20 $log = $this->api->getLogger();
21 $log->info(($response->getHeader("X-Cache-Time") ? "cached" : "enqueued")." -> response", [
22 "url" => (string) $url,
23 "info" => $response->getInfo(),
24 ]);
25
26 if ($response->getResponseCode() >= 400) {
27 $e = new RequestException($response);
28
29 $log->critical(__FUNCTION__.": ".$e->getMessage(), [
30 "url" => (string) $url,
31 ]);
32
33 throw $e;
34 }
35
36 if (!($type = $response->getHeader("Content-Type", Header::class))) {
37 $e = new RequestException($response);
38 $log->error(
39 __FUNCTION__.": Empty Content-Type -> ".$e->getMessage(), [
40 "url" => (string) $url,
41 ]);
42 throw $e;
43 }
44
45 try {
46 $type = new API\ContentType($type);
47 $data = $type->parseBody($response->getBody());
48
49 if (($link = $response->getHeader("Link", Header::class))) {
50 $links = new API\Links($link);
51 } else {
52 $links = null;
53 }
54
55 $this->api = $this->api->with(compact("type", "data", "links"));
56 } catch (\Exception $e) {
57 $log->error(__FUNCTION__.": ".$e->getMessage(), [
58 "url" => (string) $url
59 ]);
60
61 throw $e;
62 }
63
64 return $this->api;
65 }
66 }