|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace GeminiLabs\SiteReviews; |
|
4
|
|
|
|
|
5
|
|
|
use GeminiLabs\SiteReviews\Helpers\Arr; |
|
6
|
|
|
use GeminiLabs\SiteReviews\Helpers\Cast; |
|
7
|
|
|
|
|
8
|
|
|
class Response |
|
9
|
|
|
{ |
|
10
|
|
|
public array $body; |
|
11
|
|
|
public int $code; |
|
12
|
|
|
public bool $error = false; |
|
13
|
|
|
public string $message; |
|
14
|
|
|
public array $response; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param array|\WP_Error $request |
|
18
|
|
|
*/ |
|
19
|
|
|
public function __construct($request = []) |
|
20
|
|
|
{ |
|
21
|
|
|
$body = json_decode(wp_remote_retrieve_body($request), true); |
|
22
|
|
|
$this->body = Cast::toArray($body); |
|
23
|
|
|
$this->code = Cast::toInt(wp_remote_retrieve_response_code($request)); |
|
24
|
|
|
$this->message = Arr::getAs('string', $body, 'message', wp_remote_retrieve_response_message($request)); |
|
25
|
|
|
$this->response = Arr::getAs('array', $request, 'http_response'); |
|
26
|
|
|
if (is_wp_error($request)) { |
|
27
|
|
|
$this->error = true; |
|
28
|
|
|
$this->message = $request->get_error_message(); |
|
29
|
|
|
glsr_log()->error($this->message); |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function body(): array |
|
34
|
|
|
{ |
|
35
|
|
|
$body = Arr::consolidate($this->body); |
|
36
|
|
|
$body = array_map('maybe_unserialize', $body); |
|
37
|
|
|
return $body; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function data(): array |
|
41
|
|
|
{ |
|
42
|
|
|
$data = Arr::getAs('array', $this->body, 'data'); |
|
43
|
|
|
$data = array_map('maybe_unserialize', $data); |
|
44
|
|
|
return $data; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function failed(): bool |
|
48
|
|
|
{ |
|
49
|
|
|
return !$this->successful(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function shouldRetry(): bool |
|
53
|
|
|
{ |
|
54
|
|
|
return 429 === $this->code // Too-Many-Requests |
|
55
|
|
|
|| $this->code >= 500; // Internal errors |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function successful(): bool |
|
59
|
|
|
{ |
|
60
|
|
|
return false === $this->error |
|
61
|
|
|
&& $this->code >= 200 |
|
62
|
|
|
&& $this->code <= 299; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|