Client.php
71 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\WpHelper\Requests; |
| 4 | |
| 5 | defined('ABSPATH') || exit; |
| 6 | |
| 7 | class Client |
| 8 | { |
| 9 | private string $api_url; |
| 10 | private array $default_headers; |
| 11 | |
| 12 | public function __construct($api_url, $default_headers = array()) |
| 13 | { |
| 14 | $this->api_url = $api_url; |
| 15 | $this->default_headers = $default_headers; |
| 16 | } |
| 17 | |
| 18 | public function get_api_url(): string |
| 19 | { |
| 20 | return $this->api_url; |
| 21 | } |
| 22 | |
| 23 | public function set_api_url(string $api_url): void |
| 24 | { |
| 25 | $this->api_url = $api_url; |
| 26 | } |
| 27 | |
| 28 | public function get_default_headers(): array |
| 29 | { |
| 30 | return $this->default_headers; |
| 31 | } |
| 32 | |
| 33 | public function set_default_headers(array $default_headers): void |
| 34 | { |
| 35 | $this->default_headers = $default_headers; |
| 36 | } |
| 37 | |
| 38 | public function get($endpoint, $params = array(), $headers = array(), $timeout = 120) |
| 39 | { |
| 40 | $url = $this->api_url . $endpoint; |
| 41 | $request_args = array( |
| 42 | 'method' => 'GET', |
| 43 | 'headers' => array_merge($this->default_headers, $headers), |
| 44 | 'timeout' => $timeout, |
| 45 | ); |
| 46 | |
| 47 | if (! empty($params)) { |
| 48 | $url = add_query_arg($params, $url); |
| 49 | } |
| 50 | |
| 51 | $response = wp_remote_get($url, $request_args); |
| 52 | |
| 53 | return $response; |
| 54 | } |
| 55 | |
| 56 | public function post($endpoint, $params = array(), $headers = array(), $timeout = 120) |
| 57 | { |
| 58 | $url = $this->api_url . $endpoint; |
| 59 | $request_args = array( |
| 60 | 'method' => 'POST', |
| 61 | 'timeout' => $timeout, |
| 62 | 'headers' => array_merge($this->default_headers, $headers), |
| 63 | 'body' => $params, |
| 64 | ); |
| 65 | |
| 66 | $response = wp_remote_post($url, $request_args); |
| 67 | |
| 68 | return $response; |
| 69 | } |
| 70 | } |
| 71 |