| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* @package Logtivity |
| 5 |
* @copyright 2025-2026 Logtivity. All rights reserved |
| 6 |
* @contact logtivity.io, hello@logtivity.io |
| 7 |
* |
| 8 |
* This file is part of Logtivity |
| 9 |
*/ |
| 10 |
|
| 11 |
class Logtivity_Response |
| 12 |
{ |
| 13 |
/** |
| 14 |
* @var ?int |
| 15 |
*/ |
| 16 |
public ?int $code = null; |
| 17 |
|
| 18 |
/** |
| 19 |
* @var ?string |
| 20 |
*/ |
| 21 |
public ?string $message = null; |
| 22 |
|
| 23 |
/** |
| 24 |
* @var ?string |
| 25 |
*/ |
| 26 |
public ?string $error = null; |
| 27 |
|
| 28 |
/** |
| 29 |
* @var ?array |
| 30 |
*/ |
| 31 |
public ?array $body = null; |
| 32 |
|
| 33 |
/** |
| 34 |
* @var array |
| 35 |
*/ |
| 36 |
public array $request = [ |
| 37 |
'method' => 'POST', |
| 38 |
'timeout' => 0.01, |
| 39 |
'blocking' => false, |
| 40 |
'redirection' => 5, |
| 41 |
'httpversion' => '1.0', |
| 42 |
'body' => null, |
| 43 |
'cookies' => [], |
| 44 |
]; |
| 45 |
|
| 46 |
/** |
| 47 |
* @var null|array|WP_Error |
| 48 |
*/ |
| 49 |
public $response = null; |
| 50 |
|
| 51 |
public function __construct(string $apikey, string $url, array $request) |
| 52 |
{ |
| 53 |
$this->request = array_merge( |
| 54 |
$this->request, |
| 55 |
[ |
| 56 |
'headers' => [ |
| 57 |
'Authorization' => 'Bearer ' . $apikey, |
| 58 |
], |
| 59 |
], |
| 60 |
$request |
| 61 |
); |
| 62 |
|
| 63 |
$api = new Logtivity_Api(); |
| 64 |
|
| 65 |
$this->response = wp_remote_request($api->getEndpoint($url), $this->request); |
| 66 |
|
| 67 |
$this->processResponse(); |
| 68 |
} |
| 69 |
|
| 70 |
protected function processResponse(): void |
| 71 |
{ |
| 72 |
if ($this->response instanceof WP_Error) { |
| 73 |
$this->code = 500; |
| 74 |
$this->message = $this->response->get_error_code(); |
| 75 |
$this->error = $this->response->get_error_message() ?: $this->response->get_error_code(); |
| 76 |
$this->body = get_object_vars($this->response); |
| 77 |
|
| 78 |
} else { |
| 79 |
$this->code = wp_remote_retrieve_response_code($this->response); |
| 80 |
$this->message = wp_remote_retrieve_response_message($this->response); |
| 81 |
$this->body = json_decode(wp_remote_retrieve_body($this->response), true); |
| 82 |
|
| 83 |
if ($this->code < 400) { |
| 84 |
$this->error = $responseBody['error'] ?? null; |
| 85 |
|
| 86 |
} else { |
| 87 |
$this->error = $this->message; |
| 88 |
$this->message = (($this->body['message'] ?? $this->message) ?: 'Unknown error'); |
| 89 |
} |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
|