Completed
Push — master ( e8241e...60d0c3 )
by
unknown
04:24 queued 02:47
created

Curl   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 104
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 70.27%

Importance

Changes 0
Metric Value
wmc 16
lcom 0
cbo 1
dl 0
loc 104
ccs 26
cts 37
cp 0.7027
rs 10
c 0
b 0
f 0

3 Methods

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