Completed
Push — master ( ac7d60...f9cacf )
by Denis
04:30
created

Curl::getResponse()   C

Complexity

Conditions 14
Paths 33

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 15.42

Importance

Changes 0
Metric Value
dl 0
loc 59
ccs 25
cts 31
cp 0.8065
rs 6.4055
c 0
b 0
f 0
cc 14
eloc 34
nc 33
nop 5
crap 15.42

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 11
    public static function getResponse($host, $url, $method, $token, array $params)
28
    {
29 11
        $curl = curl_init();
30
31
        switch ($method) {
32 11
            case 'GET':
33 10
                if (!empty($params)) {
34 7
                    $url = sprintf("%s?%s", $url, http_build_query($params));
35
                };
36
37 10
                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 11
            'X-Auth-Token: ' . $token,
51 11
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
52 11
            'Accept: application/json'
53
        ];
54
55 11
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
56 11
        curl_setopt($curl, CURLOPT_URL, $host . $url);
57 11
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
58 11
        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 11
        Debuger::dump($method . ' ' . $host . $url . ' ' . ($method == 'POST' || $method == 'PUT' || $method == 'DELETE' ? Curl::arrayPrettyPrint($params) : ''));
65
66 11
        $curlResult = curl_exec($curl);
67
68 11
        Debuger::dump('Response code: ' . (curl_errno($curl) ? '!!! Error !!!' :  curl_getinfo($curl)['http_code']) . "\n");
69
70 11
        if (curl_errno($curl)) {
71
            return Curl::getError('Curl error: ' . curl_errno($curl), 500);
72
        }
73
74 11
        $response = json_decode($curlResult, true);
75
76 11
        if (json_last_error()) {
77
            return Curl::getError('JSON error: ' . json_last_error_msg() . "\n" . $curlResult, curl_getinfo($curl)['http_code']);
78
        }
79
80 11
        if (empty($response)) {
81
            return Curl::getError('Response is empty', curl_getinfo($curl)['http_code']);
82
        }
83
84 11
        return $response;
85
    }
86
87
    /**
88
     * Получение массива как строку
89
     *
90
     * @param array $array Данные массива
91
     *
92
     * @return mixed
93
     */
94 1
    private static function arrayPrettyPrint(array $array)
95
    {
96 1
        return str_replace('Array (', '(', preg_replace('/\s{2,}/', ' ', preg_replace('/[\x00-\x1F\x7F ]/', ' ', print_r($array, true))));
97
    }
98
99
    /**
100
     *  Дефолтный ответ при ошибке
101
     *
102
     * @param string $message Сообщение об ошибке
103
     * @param int $code Статус код ошибки
104
     *
105
     * @return array
106
     */
107
    private static function getError($message, $code)
108
    {
109
        return [
110
            'type' => 'none',
111
            'data' => null,
112
            'count' => 0,
113
            'status' => $code,
114
            'message' => $message
115
        ];
116
    }
117
}