PluginProbe
Site Reviews / trunk
Site Reviews vtrunk
8.3.1 8.3.0 8.2.2 8.2.1 8.2.0 8.1.0 8.0.13 8.0.12 8.0.11 trunk 1.2.2 2.17.1 3.5.4 4.7.0 5.25.1 6.11.8 7.0.10 7.0.11 7.0.12 7.0.13 7.0.14 7.0.15 7.0.16 7.0.17 7.0.18 All 54 releases
site-reviews / plugin / Response.php

Response.php in Site Reviews trunk, at plugin/Response.php

96 lines 2.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace GeminiLabs\SiteReviews;
4
5 use GeminiLabs\SiteReviews\Helpers\Arr;
6 use GeminiLabs\SiteReviews\Helpers\Cast;
7 use WpOrg\Requests\Utility\CaseInsensitiveDictionary;
8
9 class Response
10 {
11 public array $body = [];
12 public int $code = 0;
13 public bool $error = false;
14 public string $message = '';
15 public ?\WP_HTTP_Requests_Response $response = null;
16 public ?CaseInsensitiveDictionary $headers = null;
17
18 /**
19 * @param array|\WP_Error $request
20 */
21 public function __construct($request = [])
22 {
23 if (empty($request)) {
24 return;
25 }
26 if (is_wp_error($request)) {
27 $this->body = [];
28 $this->code = 0;
29 $this->error = true;
30 $this->headers = new CaseInsensitiveDictionary([]);
31 $this->message = $request->get_error_message();
32 $this->response = null;
33 glsr_log()->error($this->message);
34 return;
35 }
36 $responseBody = wp_remote_retrieve_body($request);
37 $body = json_decode($responseBody, true);
38 if (json_last_error() !== \JSON_ERROR_NONE) {
39 $body = [
40 'result' => $responseBody,
41 ];
42 }
43 $headers = wp_remote_retrieve_headers($request);
44 if (empty($headers)) {
45 $headers = new CaseInsensitiveDictionary([]);
46 }
47 $this->body = Cast::toArray($body);
48 $this->code = Cast::toInt(wp_remote_retrieve_response_code($request));
49 $this->headers = $headers;
50 $this->message = Arr::getAs('string', $this->body, 'message', wp_remote_retrieve_response_message($request));
51 $this->response = $request['http_response'] ?? null;
52 }
53
54 public function body(): array
55 {
56 return $this->unserialized($this->body);
57 }
58
59 public function data(): array
60 {
61 return $this->unserialized(Arr::getAs('array', $this->body, 'data'));
62 }
63
64 public function failed(): bool
65 {
66 return !$this->successful();
67 }
68
69 public function shouldRetry(): bool
70 {
71 return 429 === $this->code // Too-Many-Requests
72 || $this->code >= 500; // Internal errors
73 }
74
75 public function successful(): bool
76 {
77 return false === $this->error
78 && $this->code >= 200
79 && $this->code <= 299;
80 }
81
82 /**
83 * Some APIs send values as serialized PHP. The bytes arrive over the network, so
84 * they must never restore an object: unserialize() runs its magic methods first.
85 */
86 protected function unserialized(array $values): array
87 {
88 return array_map(function ($value) {
89 if (!is_serialized($value)) {
90 return $value;
91 }
92 return @unserialize(trim($value), ['allowed_classes' => false]);
93 }, $values);
94 }
95 }
96