1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Blackmine\Client\Response; |
6
|
|
|
|
7
|
|
|
use JsonException; |
8
|
|
|
use Requests_Response; |
9
|
|
|
|
10
|
|
|
class ApiResponse |
11
|
|
|
{ |
12
|
|
|
protected bool $is_cached; |
13
|
|
|
|
14
|
|
|
public function __construct(protected int | bool $status, protected ?array $data) |
15
|
|
|
{ |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @throws JsonException |
20
|
|
|
*/ |
21
|
|
|
public static function fromRequestsResponse(Requests_Response $response, bool $is_cached = false): self |
22
|
|
|
{ |
23
|
|
|
$data = |
24
|
|
|
($response->body !== '' && self::isJson($response)) ? |
25
|
|
|
json_decode($response->body, true, 512, JSON_THROW_ON_ERROR) : []; |
26
|
|
|
|
27
|
|
|
$ret = new self( |
28
|
|
|
$response->status_code, |
29
|
|
|
$data |
30
|
|
|
); |
31
|
|
|
|
32
|
|
|
$ret->setIsCached($is_cached); |
33
|
|
|
|
34
|
|
|
return $ret; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function getStatus(): int|bool |
38
|
|
|
{ |
39
|
|
|
return $this->status; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function getData(): ?array |
43
|
|
|
{ |
44
|
|
|
return $this->data; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function isCached(): bool |
48
|
|
|
{ |
49
|
|
|
return $this->is_cached; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function isSuccess(): bool |
53
|
|
|
{ |
54
|
|
|
return $this->status >= 200 && $this->status < 300; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function isPaginated(): bool |
58
|
|
|
{ |
59
|
|
|
return isset($this->data["limit"], $this->data["total_count"], $this->data["offset"]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function setStatus(int $status): void |
63
|
|
|
{ |
64
|
|
|
$this->status = $status; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function setData(?array $data): void |
68
|
|
|
{ |
69
|
|
|
$this->data = $data; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function setIsCached(bool $is_cached): void |
73
|
|
|
{ |
74
|
|
|
$this->is_cached = $is_cached; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
public function getLimit(): ?int |
78
|
|
|
{ |
79
|
|
|
if ($this->isPaginated()) { |
80
|
|
|
return $this->data["limit"]; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
return null; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
public function getTotalCount(): ?int |
87
|
|
|
{ |
88
|
|
|
if ($this->isPaginated()) { |
89
|
|
|
return $this->data["total_count"]; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return null; |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
public function getOffset(): ?int |
96
|
|
|
{ |
97
|
|
|
if ($this->isPaginated()) { |
98
|
|
|
return $this->data["offset"]; |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
return null; |
102
|
|
|
} |
103
|
|
|
|
104
|
|
|
private static function isJson(Requests_Response $response): bool |
105
|
|
|
{ |
106
|
|
|
return str_contains((string) $response->headers->getValues("Content-Type")[0], "application/json"); |
107
|
|
|
} |
108
|
|
|
} |
109
|
|
|
|