Curl   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 64.85%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 0
dl 0
loc 109
ccs 24
cts 37
cp 0.6485
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getError() 0 10 1
C getResponse() 0 62 10
A arrayPrettyPrint() 0 4 1
1
<?php
2
/**
3
 * Class Curl
4
 *
5
 * @author       Denis Shestakov <[email protected]>
6
 * @copyright    Copyright (c) 2017, Lan Publishing
7
 * @license      MIT
8
 */
9
10
namespace Lan\Ebs\Sdk\Helper;
11
12
use Exception;
13
14
/**
15
 * Хелпер для работы с curl
16
 *
17
 * @package      Lan\Ebs
18
 * @subpackage   Sdk
19
 * @category     Helper
20
 */
21
class Curl
22
{
23
    /**
24
     * Получение ответа от сервера API
25
     *
26
     * @param string $host Домен сервера API
27
     * @param string $url Урл ресурса API
28
     * @param string $method Метод http-запроса (GET|POST|PUT|DELETE)
29
     * @param string $token Токен клиента
30
     * @param array $params Параметры, переданные серверу API
31
     *
32
     * @return array|mixed
33
     *
34
     * @throws Exception
35
     */
36 10
    public static function getResponse($host, $url, $method, $token, array $params)
37
    {
38 10
        $curl = curl_init();
39
40
        switch ($method) {
41 10
            case 'GET':
42 9
                if (!empty($params)) {
43 7
                    $url = sprintf("%s?%s", $url, http_build_query($params, '', '&'));
44
                };
45
46 9
                break;
47 1
            case 'POST':
48
            case 'PUT':
49
            case 'DELETE':
50 1
                if (!empty($params)) {
51 1
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params, '', '&'));
52
                }
53 1
                break;
54
            default:
55
                throw new Exception('Method ' . $method . ' unknown');
56
        }
57
58
//        $url = html_entity_decode($url);
59
60
        $headers = array(
61 10
            'X-Auth-Token: ' . $token,
62 10
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
63 10
            'Accept: application/json'
64
        );
65
66 10
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
67 10
        curl_setopt($curl, CURLOPT_URL, $host . $url);
68 10
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
69 10
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
70 10
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
71
72
//        $fp = fopen(__DIR__ . '/errorlog.txt', 'w');
73
//        curl_setopt($curl, CURLOPT_VERBOSE, 1);
74
//        curl_setopt($curl, CURLOPT_STDERR, $fp);
75
76
        //Debuger::dump($method . ' ' . $host . $url . ' ' . ($method === 'POST' || $method === 'PUT' || $method === 'DELETE' ? Curl::arrayPrettyPrint($params) : ''));
77
78 10
        $curlResult = curl_exec($curl);
79
80
        //Debuger::dump('Response code: ' . (curl_errno($curl) ? '!!! Error !!!' : curl_getinfo($curl)['http_code']) . "\n");
81
82 10
        if (curl_errno($curl)) {
83
            return Curl::getError('Curl error ' . curl_errno($curl) . ': ' . curl_error($curl), 500);
84
        }
85
86 10
        $response = json_decode($curlResult, true);
87
88 10
        if (json_last_error()) {
89
            return Curl::getError('JSON error ' . json_last_error() . ': ' . json_last_error_msg() . "\n" . $curlResult, curl_getinfo($curl)['http_code']);
90
        }
91
92 10
        if (empty($response)) {
93
            return Curl::getError('Response is empty', curl_getinfo($curl)['http_code']);
94
        }
95
96 10
        return $response;
97
    }
98
99
    /**
100
     * Получение массива как строку
101
     *
102
     * @param array $array Данные массива
103
     *
104
     * @return mixed
105
     */
106
    private static function arrayPrettyPrint(array $array)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
107
    {
108
        return str_replace('Array (', '(', preg_replace('/\s{2,}/', ' ', preg_replace('/[\x00-\x1F\x7F ]/', ' ', print_r($array, true))));
109
    }
110
111
    /**
112
     *  Дефолтный ответ при ошибке
113
     *
114
     * @param string $message Сообщение об ошибке
115
     * @param int $code Статус код ошибки
116
     *
117
     * @return array
118
     */
119
    private static function getError($message, $code)
120
    {
121
        return array(
122
            'type' => 'none',
123
            'data' => null,
124
            'count' => 0,
125
            'status' => $code,
126
            'message' => $message
127
        );
128
    }
129
}