1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: dp |
5
|
|
|
* Date: 26.07.17 |
6
|
|
|
* Time: 12:06 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Lan\Ebs\Sdk\Helper; |
10
|
|
|
|
11
|
|
|
use Exception; |
12
|
|
|
|
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) |
70
|
|
|
{ |
71
|
|
|
return [ |
72
|
1 |
|
'type' => 'none', |
73
|
|
|
'data' => null, |
74
|
1 |
|
'count' => 0, |
75
|
1 |
|
'status' => $code, |
76
|
1 |
|
'message' => $message |
77
|
|
|
]; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
private static function arrayPrettyPrint(array $array) { |
81
|
|
|
return str_replace('Array (', '(', preg_replace('/\s{2,}/', ' ', preg_replace('/[\x00-\x1F\x7F ]/', ' ', print_r($array, true)))); |
82
|
|
|
} |
83
|
|
|
} |