Completed
Push — master ( 6a8aa6...5393ba )
by dotzero
03:56
created

Request::request()   F

Complexity

Conditions 13
Paths 336

Size

Total Lines 83
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 83
ccs 0
cts 62
cp 0
rs 3.7737
cc 13
eloc 53
nc 336
nop 2
crap 182

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 AmoCRM\Request;
4
5
use AmoCRM\Exception;
6
use AmoCRM\NetworkException;
7
8
/**
9
 * Class Request
10
 *
11
 * Класс отправляющий запросы к API amoCRM используя cURL
12
 *
13
 * @package AmoCRM\Request
14
 * @author dotzero <[email protected]>
15
 * @link http://www.dotzero.ru/
16
 * @link https://github.com/dotzero/amocrm-php
17
 *
18
 * For the full copyright and license information, please view the LICENSE
19
 * file that was distributed with this source code.
20
 */
21
class Request
22
{
23
    /**
24
     * @var bool Использовать устаревшую схему авторизации
25
     */
26
    protected $v1 = false;
27
28
    /**
29
     * @var bool Флаг вывода отладочной информации
30
     */
31
    private $debug = false;
32
33
    /**
34
     * @var ParamsBag|null Экземпляр ParamsBag для хранения аргументов
35
     */
36
    private $parameters = null;
37
38
    /**
39
     * Request constructor
40
     *
41
     * @param ParamsBag $parameters Экземпляр ParamsBag для хранения аргументов
42
     * @throws NetworkException
43
     */
44 108
    public function __construct(ParamsBag $parameters)
45
    {
46 108
        if (!function_exists('curl_init')) {
47
            throw new NetworkException('The cURL PHP extension was not loaded');
48
        }
49
50 108
        $this->parameters = $parameters;
51 108
    }
52
53
    /**
54
     * Установка флага вывода отладочной информации
55
     *
56
     * @param bool $flag Значение флага
57
     * @return $this
58
     */
59 1
    public function debug($flag = false)
60
    {
61 1
        $this->debug = (bool)$flag;
62
63 1
        return $this;
64
    }
65
66
    /**
67
     * Выполнить HTTP GET запрос и вернуть тело ответа
68
     *
69
     * @param string $url Запрашиваемый URL
70
     * @param array $parameters Список GET параметров
71
     * @param null|string $modified Значение заголовка IF-MODIFIED-SINCE
72
     * @return mixed
73
     * @throws Exception
74
     * @throws NetworkException
75
     */
76 1
    protected function getRequest($url, $parameters = [], $modified = null)
77
    {
78 1
        if (!empty($parameters)) {
79 1
            $this->parameters->addGet($parameters);
80 1
        }
81
82 1
        return $this->request($url, $modified);
83
    }
84
85
    /**
86
     * Выполнить HTTP POST запрос и вернуть тело ответа
87
     *
88
     * @param string $url Запрашиваемый URL
89
     * @param array $parameters Список POST параметров
90
     * @return mixed
91
     * @throws Exception
92
     * @throws NetworkException
93
     */
94 1
    protected function postRequest($url, $parameters = [])
95
    {
96 1
        if (!empty($parameters)) {
97 1
            $this->parameters->addPost($parameters);
98 1
        }
99
100 1
        return $this->request($url);
101
    }
102
103
    /**
104
     * Выполнить HTTP запрос и вернуть тело ответа
105
     *
106
     * @param string $url Запрашиваемый URL
107
     * @param null|string $modified Значение заголовка IF-MODIFIED-SINCE
108
     * @return mixed
109
     * @throws Exception
110
     * @throws NetworkException
111
     */
112
    protected function request($url, $modified = null)
113
    {
114
        $headers = ['Content-Type: application/json'];
115
116
        if ($modified !== null) {
117
            $headers[] = 'IF-MODIFIED-SINCE: ' . (new \DateTime($modified))->format(\DateTime::RFC1123);
118
        }
119
120
        if ($this->v1 === false) {
121
            $query = http_build_query(array_merge($this->parameters->getGet(), [
122
                'USER_LOGIN' => $this->parameters->getAuth('login'),
123
                'USER_HASH' => $this->parameters->getAuth('apikey'),
124
            ]));
125
        } else {
126
            $query = http_build_query(array_merge($this->parameters->getGet(), [
127
                'login' => $this->parameters->getAuth('login'),
128
                'api_key' => $this->parameters->getAuth('apikey'),
129
            ]));
130
        }
131
132
        $endpoint = sprintf('https://%s.amocrm.ru%s?%s', $this->parameters->getAuth('domain'), $url, $query);
133
134
        if ($this->debug) {
135
            printf('[DEBUG] url: %s' . PHP_EOL, $endpoint);
136
            printf('[DEBUG] headers: %s' . PHP_EOL, print_r($headers, 1));
137
            if ($this->parameters->hasPost()) {
138
                printf('[DEBUG] post: %s' . PHP_EOL, json_encode([
139
                    'request' => $this->parameters->getPost(),
140
                ]));
141
            }
142
        }
143
144
        $ch = curl_init();
145
146
        curl_setopt($ch, CURLOPT_URL, $endpoint);
147
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
148
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
149
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
150
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
151
152
        if ($this->parameters->hasPost()) {
153
            curl_setopt($ch, CURLOPT_POST, true);
154
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
155
                'request' => $this->parameters->getPost(),
156
            ]));
157
        }
158
159
        $result = curl_exec($ch);
160
        $info = curl_getinfo($ch);
161
        $error = curl_error($ch);
162
        $errno = curl_errno($ch);
163
164
        curl_close($ch);
165
166
        if ($this->debug) {
167
            printf('[DEBUG] curl_exec: %s' . PHP_EOL, $result);
168
            printf('[DEBUG] curl_getinfo: %s' . PHP_EOL, print_r($info, 1));
169
            printf('[DEBUG] curl_error: %s' . PHP_EOL, $error);
170
            printf('[DEBUG] curl_errno: %s' . PHP_EOL, $errno);
171
        }
172
173
        if ($error) {
174
            throw new NetworkException($error, $errno);
175
        }
176
177
        $result = json_decode($result, true);
178
179
        if (!isset($result['response'])) {
180
            return false;
181
        } elseif (floor($info['http_code'] / 100) >= 3) {
182
            $code = 0;
183
            if (isset($result['response']['error_code']) && $result['response']['error_code'] > 0) {
184
                $code = $result['response']['error_code'];
185
            }
186
            if ($this->v1 === false) {
187
                throw new Exception($result['response']['error'], $code);
188
            } else {
189
                throw new Exception(json_encode($result['response']), $code);
190
            }
191
        }
192
193
        return $result['response'];
194
    }
195
}
196