1 | <?php |
||
13 | class Curl |
||
14 | { |
||
15 | 16 | public static function getResponse($host, $url, $method, $token, array $params) |
|
16 | { |
||
17 | 16 | $curl = curl_init(); |
|
18 | |||
19 | switch ($method) { |
||
20 | 16 | case 'GET': |
|
21 | 15 | if (!empty($params)) { |
|
22 | 11 | $url = sprintf("%s?%s", $url, http_build_query($params)); |
|
23 | }; |
||
24 | |||
25 | 15 | break; |
|
26 | 2 | case 'POST': |
|
27 | 1 | case 'PUT': |
|
28 | case 'DELETE': |
||
29 | 2 | if (!empty($params)) { |
|
30 | 2 | curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params)); |
|
31 | } |
||
32 | 2 | break; |
|
33 | default: |
||
34 | throw new Exception('Method ' . $method . ' unknown'); |
||
35 | } |
||
36 | |||
37 | $headers = [ |
||
38 | 16 | 'X-Auth-Token: ' . $token, |
|
39 | 16 | 'Content-Type: application/x-www-form-urlencoded; charset=utf-8', |
|
40 | 16 | 'Accept: application/json' |
|
41 | ]; |
||
42 | |||
43 | 16 | curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); |
|
44 | 16 | curl_setopt($curl, CURLOPT_URL, $host . $url); |
|
45 | 16 | curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
|
46 | 16 | curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); |
|
47 | |||
48 | 16 | $curlResult = curl_exec($curl); |
|
49 | |||
50 | 16 | Debuger::dump($method . ' ' . $host . $url . ' ' . ($method == 'POST' || $method == 'PUT' || $method == 'DELETE' ? Curl::arrayPrettyPrint($params) : '') . '[' . (curl_errno($curl) ? 500 : curl_getinfo($curl)['http_code']) . ']'); |
|
51 | |||
52 | 16 | if (curl_errno($curl)) { |
|
53 | return Curl::getError('Curl error: ' . curl_errno($curl), 500); |
||
54 | } |
||
55 | |||
56 | 16 | $response = json_decode($curlResult, true); |
|
57 | |||
58 | 16 | if (json_last_error()) { |
|
59 | 1 | return Curl::getError('JSON error: ' . json_last_error_msg() . "\n" . $curlResult, curl_getinfo($curl)['http_code']); |
|
60 | } |
||
61 | |||
62 | 15 | if (empty($response)) { |
|
63 | return Curl::getError('Response is empty', curl_getinfo($curl)['http_code']); |
||
64 | } |
||
65 | |||
66 | 15 | return $response; |
|
67 | } |
||
68 | |||
69 | 1 | private static function getError($message, $code) |
|
79 | |||
80 | private static function arrayPrettyPrint(array $array) { |
||
83 | } |