Requests
11 months ago
CurlHttpClient.php
11 months ago
DummyHttpClient.php
11 months ago
WordPressHttpClient.php
11 months ago
CurlHttpClient.php
103 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Analyst\Http; |
| 4 | |
| 5 | use Analyst\ApiResponse; |
| 6 | use Analyst\Contracts\HttpClientContract; |
| 7 | |
| 8 | class CurlHttpClient implements HttpClientContract |
| 9 | { |
| 10 | /** |
| 11 | * Make an http request |
| 12 | * |
| 13 | * @param $method |
| 14 | * @param $url |
| 15 | * @param array $body |
| 16 | * @param $headers |
| 17 | * @return mixed |
| 18 | */ |
| 19 | public function request($method, $url, $body, $headers) |
| 20 | { |
| 21 | $method = strtoupper($method); |
| 22 | |
| 23 | $options = [ |
| 24 | CURLOPT_RETURNTRANSFER => true, |
| 25 | CURLOPT_URL => $url, |
| 26 | CURLOPT_HTTPHEADER => $this->prepareRequestHeaders($headers), |
| 27 | CURLOPT_CUSTOMREQUEST => $method, |
| 28 | CURLOPT_FAILONERROR => true, |
| 29 | CURLOPT_HEADER => true, |
| 30 | CURLOPT_TIMEOUT => 30, |
| 31 | ]; |
| 32 | |
| 33 | if ($method === 'POST') { |
| 34 | $options[CURLOPT_POST] = 1; |
| 35 | $options[CURLOPT_POSTFIELDS] = json_encode($body); |
| 36 | } |
| 37 | |
| 38 | $curl = curl_init(); |
| 39 | |
| 40 | curl_setopt_array($curl, $options); |
| 41 | |
| 42 | $response = curl_exec($curl); |
| 43 | |
| 44 | list($rawHeaders, $rawBody) = explode("\r\n\r\n", $response, 2); |
| 45 | |
| 46 | $info = curl_getinfo($curl); |
| 47 | |
| 48 | curl_close($curl); |
| 49 | |
| 50 | $responseHeaders = $this->resolveResponseHeaders($rawHeaders); |
| 51 | $responseBody = json_decode($rawBody, true); |
| 52 | |
| 53 | return new ApiResponse($responseBody, $info['http_code'], $responseHeaders); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Must return `true` if client is supported |
| 58 | * |
| 59 | * @return bool |
| 60 | */ |
| 61 | public static function hasSupport() |
| 62 | { |
| 63 | return function_exists('curl_version'); |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Modify request headers from key value pair |
| 68 | * to vector array |
| 69 | * |
| 70 | * @param array $headers |
| 71 | * @return array |
| 72 | */ |
| 73 | protected function prepareRequestHeaders ($headers) |
| 74 | { |
| 75 | return array_map(function ($key, $value) { |
| 76 | return sprintf('%s:%s', $key, $value); |
| 77 | }, array_keys($headers), $headers); |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Resolve raw response headers as |
| 82 | * associative array |
| 83 | * |
| 84 | * @param $rawHeaders |
| 85 | * @return array |
| 86 | */ |
| 87 | private function resolveResponseHeaders($rawHeaders) |
| 88 | { |
| 89 | $headers = []; |
| 90 | |
| 91 | foreach (explode("\r\n", $rawHeaders) as $i => $line) { |
| 92 | $parts = explode(': ', $line); |
| 93 | |
| 94 | if (count($parts) === 1) { |
| 95 | continue; |
| 96 | } |
| 97 | |
| 98 | $headers[$parts[0]] = $parts[1]; |
| 99 | } |
| 100 | return $headers; |
| 101 | } |
| 102 | } |
| 103 |