Completed
Push — master ( b06c4a...1da428 )
by Denis
36:46 queued 33:46
created

Curl   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 77.5%

Importance

Changes 0
Metric Value
wmc 16
lcom 0
cbo 1
dl 0
loc 109
ccs 31
cts 40
cp 0.775
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
C getResponse() 0 62 14
A arrayPrettyPrint() 0 4 1
A getError() 0 10 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 13
    public static function getResponse($host, $url, $method, $token, array $params)
37
    {
38 13
        $curl = curl_init();
39
40 13
        switch ($method) {
41 13
            case 'GET':
42 11
                if (!empty($params)) {
43 8
                    $url = sprintf("%s?%s", $url, http_build_query($params));
44
                };
45
46 11
                break;
47 3
            case 'POST':
48 2
            case 'PUT':
49 1
            case 'DELETE':
50 3
                if (!empty($params)) {
51 2
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
52
                }
53 3
                break;
54
            default:
55
                throw new Exception('Method ' . $method . ' unknown');
56
        }
57
58
//        $url = html_entity_decode($url);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
59
60
        $headers = [
61 13
            'X-Auth-Token: ' . $token,
62 13
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
63 13
            'Accept: application/json'
64
        ];
65
66 13
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
67 13
        curl_setopt($curl, CURLOPT_URL, $host . $url);
68 13
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
69 13
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
70 13
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
71
72
//        $fp = fopen(__DIR__ . '/errorlog.txt', 'w');
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
73
//        curl_setopt($curl, CURLOPT_VERBOSE, 1);
74
//        curl_setopt($curl, CURLOPT_STDERR, $fp);
75
76 13
        Debuger::dump($method . ' ' . $host . $url . ' ' . ($method == 'POST' || $method == 'PUT' || $method == 'DELETE' ? Curl::arrayPrettyPrint($params) : ''));
77
78 13
        $curlResult = curl_exec($curl);
79
80 13
        Debuger::dump('Response code: ' . (curl_errno($curl) ? '!!! Error !!!' : curl_getinfo($curl)['http_code']) . "\n");
81
82 13
        if (curl_errno($curl)) {
83
            return Curl::getError('Curl error ' . curl_errno($curl) . ': ' . curl_error($curl), 500);
84
        }
85
86 13
        $response = json_decode($curlResult, true);
87
88 13
        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 13
        if (empty($response)) {
93
            return Curl::getError('Response is empty', curl_getinfo($curl)['http_code']);
94
        }
95
96 13
        return $response;
97
    }
98
99
    /**
100
     * Получение массива как строку
101
     *
102
     * @param array $array Данные массива
103
     *
104
     * @return mixed
105
     */
106 3
    private static function arrayPrettyPrint(array $array)
107
    {
108 3
        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 [
122
            'type' => 'none',
123
            'data' => null,
124
            'count' => 0,
125
            'status' => $code,
126
            'message' => $message
127
        ];
128
    }
129
}