|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Curl; |
| 4 | + |
| 5 | +class Client |
| 6 | +{ |
| 7 | + // Default HTTP headers |
| 8 | + protected $headers = array(); |
| 9 | + |
| 10 | + // Default cURL options |
| 11 | + protected $options = array(); |
| 12 | + |
| 13 | + public function __construct() |
| 14 | + { |
| 15 | + // do nothing |
| 16 | + } |
| 17 | + |
| 18 | + protected function buildUrl($uri, $params = array()) |
| 19 | + { |
| 20 | + if ($params) { |
| 21 | + return $uri . '?' . http_build_query($params); |
| 22 | + } |
| 23 | + |
| 24 | + return $uri; |
| 25 | + } |
| 26 | + |
| 27 | + protected function getCombinedHeaders($headers) |
| 28 | + { |
| 29 | + $headers = $this->headers + $headers; |
| 30 | + |
| 31 | + array_walk($headers, function (&$item, $key) { |
| 32 | + $item = "{$key}: {$item}"; |
| 33 | + }); |
| 34 | + |
| 35 | + return array_values($headers); |
| 36 | + } |
| 37 | + |
| 38 | + public function request($method, $uri, $params = array(), $headers = array(), $curl_options = array()) |
| 39 | + { |
| 40 | + $ch = curl_init(); |
| 41 | + |
| 42 | + if ($method == 'GET') { |
| 43 | + curl_setopt($ch, CURLOPT_URL, $this->buildUrl($uri, $params)); |
| 44 | + } else { |
| 45 | + curl_setopt($ch, CURLOPT_URL, $uri); |
| 46 | + |
| 47 | + $post_data = is_array($params) ? http_build_query($params) : $params; |
| 48 | + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); |
| 49 | + } |
| 50 | + |
| 51 | + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); |
| 52 | + |
| 53 | + curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getCombinedHeaders($headers)); |
| 54 | + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
| 55 | + curl_setopt($ch, CURLOPT_HEADER, 0); |
| 56 | + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); |
| 57 | + |
| 58 | + // last chance to override |
| 59 | + curl_setopt_array($ch, is_array($curl_options) ? ($this->options + $curl_options) : $this->options); |
| 60 | + |
| 61 | + $result = curl_exec($ch); |
| 62 | + $info = curl_getinfo($ch); |
| 63 | + |
| 64 | + $response = new Response(); |
| 65 | + $response->status = $info ? $info['http_code'] : 0; |
| 66 | + $response->body = $result; |
| 67 | + $response->error = curl_error($ch); |
| 68 | + $response->info = $info; |
| 69 | + |
| 70 | + curl_close($ch); |
| 71 | + |
| 72 | + return $response; |
| 73 | + } |
| 74 | + |
| 75 | + public function get($uri, $params = array(), $headers = array()) |
| 76 | + { |
| 77 | + return $this->request('GET', $uri, $params, $headers); |
| 78 | + } |
| 79 | + |
| 80 | + public function post($uri, $params = array(), $headers = array()) |
| 81 | + { |
| 82 | + return $this->request('POST', $uri, $params, $headers); |
| 83 | + } |
| 84 | +} |
0 commit comments