Requests
11 months ago
CurlHttpClient.php
11 months ago
DummyHttpClient.php
11 months ago
WordPressHttpClient.php
11 months ago
WordPressHttpClient.php
62 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Analyst\Http; |
| 4 | |
| 5 | use WP_Error; |
| 6 | use Analyst\ApiResponse; |
| 7 | use Analyst\Contracts\HttpClientContract; |
| 8 | use Requests_Utility_CaseInsensitiveDictionary; |
| 9 | |
| 10 | class WordPressHttpClient implements HttpClientContract |
| 11 | { |
| 12 | /** |
| 13 | * Make an http request |
| 14 | * |
| 15 | * @param $method |
| 16 | * @param $url |
| 17 | * @param $body |
| 18 | * @param $headers |
| 19 | * @return ApiResponse |
| 20 | */ |
| 21 | public function request($method, $url, $body, $headers) |
| 22 | { |
| 23 | $options = [ |
| 24 | 'body' => json_encode($body), |
| 25 | 'headers' => $headers, |
| 26 | 'method' => $method, |
| 27 | 'timeout' => 30, |
| 28 | ]; |
| 29 | |
| 30 | $response = wp_remote_request($url, $options); |
| 31 | |
| 32 | $body = []; |
| 33 | $responseHeaders = []; |
| 34 | |
| 35 | if ($response instanceof WP_Error) { |
| 36 | $code = $response->get_error_code(); |
| 37 | } else { |
| 38 | /** @var Requests_Utility_CaseInsensitiveDictionary $headers */ |
| 39 | $responseHeaders = $response['headers']->getAll(); |
| 40 | $body = json_decode($response['body'], true); |
| 41 | $code = $response['response']['code']; |
| 42 | } |
| 43 | |
| 44 | |
| 45 | return new ApiResponse( |
| 46 | $body, |
| 47 | $code, |
| 48 | $responseHeaders |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Must return `true` if client is supported |
| 54 | * |
| 55 | * @return bool |
| 56 | */ |
| 57 | public static function hasSupport() |
| 58 | { |
| 59 | return function_exists('wp_remote_request'); |
| 60 | } |
| 61 | } |
| 62 |