Completed
Push — master ( 1f7ab5...0b80d4 )
by Denis
05:55
created

Curl::getResponse()   C

Complexity

Conditions 14
Paths 33

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 14.4207

Importance

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

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
 * 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 14
    public static function getResponse($host, $url, $method, $token, array $params)
37
    {
38 14
        $curl = curl_init();
39
40
        switch ($method) {
41 14
            case 'GET':
42 12
                if (!empty($params)) {
43 8
                    $url = sprintf("%s?%s", $url, http_build_query($params));
44
                };
45
46 12
                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
        $headers = [
59 14
            'X-Auth-Token: ' . $token,
60 14
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
61 14
            'Accept: application/json'
62
        ];
63
64 14
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
65 14
        curl_setopt($curl, CURLOPT_URL, $host . $url);
66 14
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
67 14
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
68
69
//        $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...
70
//        curl_setopt($curl, CURLOPT_VERBOSE, 1);
71
//        curl_setopt($curl, CURLOPT_STDERR, $fp);
72
73 14
        Debuger::dump($method . ' ' . $host . $url . ' ' . ($method == 'POST' || $method == 'PUT' || $method == 'DELETE' ? Curl::arrayPrettyPrint($params) : ''));
74
75 14
        $curlResult = curl_exec($curl);
76
77 14
        Debuger::dump('Response code: ' . (curl_errno($curl) ? '!!! Error !!!' : curl_getinfo($curl)['http_code']) . "\n");
78
79 14
        if (curl_errno($curl)) {
80
            return Curl::getError('Curl error: ' . curl_errno($curl), 500);
81
        }
82
83 14
        $response = json_decode($curlResult, true);
84
85 14
        if (json_last_error()) {
86
            return Curl::getError('JSON error: ' . json_last_error_msg() . "\n" . $curlResult, curl_getinfo($curl)['http_code']);
87
        }
88
89 14
        if (empty($response)) {
90
            return Curl::getError('Response is empty', curl_getinfo($curl)['http_code']);
91
        }
92
93 14
        return $response;
94
    }
95
96
    /**
97
     * Получение массива как строку
98
     *
99
     * @param array $array Данные массива
100
     *
101
     * @return mixed
102
     */
103 3
    private static function arrayPrettyPrint(array $array)
104
    {
105 3
        return str_replace('Array (', '(', preg_replace('/\s{2,}/', ' ', preg_replace('/[\x00-\x1F\x7F ]/', ' ', print_r($array, true))));
106
    }
107
108
    /**
109
     *  Дефолтный ответ при ошибке
110
     *
111
     * @param string $message Сообщение об ошибке
112
     * @param int $code Статус код ошибки
113
     *
114
     * @return array
115
     */
116
    private static function getError($message, $code)
117
    {
118
        return [
119
            'type' => 'none',
120
            'data' => null,
121
            'count' => 0,
122
            'status' => $code,
123
            'message' => $message
124
        ];
125
    }
126
}