Completed
Push — master ( dd736e...c56df6 )
by dotzero
02:27
created

Request::debug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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