Completed
Push — master ( 2c3288...b4eff5 )
by Alex
02:34
created

CustomClient.php (1 issue)

Severity
1
<?php
2
namespace Mezon\CustomClient;
3
4
/**
5
 * Class CustomClient
6
 *
7
 * @package Mezon
8
 * @subpackage CustomClient
9
 * @author Dodonov A.A.
10
 * @version v.1.0 (2019/08/07)
11
 * @copyright Copyright (c) 2019, aeon.org
12
 */
13
14
/**
15
 * Custom API client class
16
 */
17
class CustomClient
18
{
19
20
    /**
21
     * Server host
22
     *
23
     * @var string
24
     */
25
    protected $url = false;
26
27
    /**
28
     * Headers
29
     *
30
     * @var array
31
     */
32
    protected $headers = false;
33
34
    /**
35
     * Idempotence key
36
     *
37
     * @var string
38
     */
39
    protected $idempotencyKey = '';
40
41
    /**
42
     * Constructor
43
     *
44
     * @param string $url
45
     *            Service URL
46
     * @param array $headers
47
     *            HTTP headers
48
     */
49
    public function __construct(string $url, array $headers = [])
50
    {
51
        if ($url === false || $url === '') {
52
            throw (new \Exception(
53
                'Service URL must be set in class ' . __CLASS__ . ' extended in ' . get_called_class() .
54
                ' and called from ' . ($_SERVER['SERVER_NAME'] ?? 'console') . ($_SERVER['REQUEST_URI'] ?? ''),
55
                - 23));
56
        }
57
58
        $this->url = rtrim($url, '/');
59
60
        $this->headers = $headers;
61
    }
62
63
    /**
64
     * Method send request to the URL
65
     *
66
     * @param string $url
67
     *            URL
68
     * @param array $headers
69
     *            Headers
70
     * @param string $method
71
     *            Request HTTP Method
72
     * @param array $data
73
     *            Request data
74
     * @return array Response body and HTTP code
75
     * @codeCoverageIgnore
76
     */
77
    protected function sendRequest(string $url, array $headers, string $method, array $data = []): array
78
    {
79
        return \Mezon\CustomClient\CurlWrapper::sendRequest($url, $headers, $method, $data);
80
    }
81
82
    /**
83
     * Method gets result and validates it.
84
     *
85
     * @param string $url
86
     *            request URL
87
     * @param int $code
88
     *            response HTTP code
89
     * @param string $body
90
     *            response body
91
     * @return mixed Request result
92
     */
93
    protected function dispatchResult(string $url, int $code, string $body)
94
    {
95
        if ($code == 404) {
96
            throw (new \Exception("URL: $url not found"));
97
        } elseif ($code == 400) {
98
            throw (new \Exception("Bad request on URL $url"));
99
        } elseif ($code == 403) {
100
            throw (new \Exception("Auth error"));
101
        }
102
103
        return $body;
104
    }
105
106
    /**
107
     * Method returns common headers
108
     *
109
     * @return array Headers
110
     */
111
    protected function getCommonHeaders(): array
112
    {
113
        $result = [];
114
115
        if ($this->headers !== false) {
0 ignored issues
show
The condition $this->headers !== false is always true.
Loading history...
116
            $result = $this->headers;
117
        }
118
119
        if ($this->idempotencyKey !== '') {
120
            $result[] = 'Idempotency-Key: ' . $this->idempotencyKey;
121
        }
122
123
        $result[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';
124
125
        return $result;
126
    }
127
128
    /**
129
     * Method compiles post headers
130
     *
131
     * @return array Header
132
     */
133
    protected function getFormHeaders(): array
134
    {
135
        $fullHeaders = $this->getCommonHeaders();
136
137
        $fullHeaders[] = 'Content-type: application/x-www-form-urlencoded';
138
139
        return $fullHeaders;
140
    }
141
142
    /**
143
     * Method sends request on server
144
     *
145
     * @param string $method
146
     *            HTTP method (POST|PUT|DELETE)
147
     * @param string $endpoint
148
     *            Calling endpoint
149
     * @param mixed $data
150
     *            Request data
151
     */
152
    protected function sendFormRequest(string $method, string $endpoint, array $data = [])
153
    {
154
        $fullUrl = $this->url . '/' . ltrim($endpoint, '/');
155
156
        list ($body, $code) = $this->sendRequest($fullUrl, $this->getFormHeaders(), $method, $data);
157
158
        return $this->dispatchResult($fullUrl, $code, $body);
159
    }
160
161
    /**
162
     * Method sends POST request to server
163
     *
164
     * @param string $endpoint
165
     *            Calling endpoint
166
     * @param array $data
167
     *            Request data
168
     * @return mixed Result of the request
169
     */
170
    public function sendPostRequest(string $endpoint, array $data = [])
171
    {
172
        return $this->sendFormRequest('POST', $endpoint, $data);
173
    }
174
175
    /**
176
     * Method sends PUT request to server
177
     *
178
     * @param string $endpoint
179
     *            Calling endpoint
180
     * @param array $data
181
     *            Request data
182
     * @return mixed Result of the request
183
     */
184
    public function sendPutRequest(string $endpoint, array $data = [])
185
    {
186
        return $this->sendFormRequest('PUT', $endpoint, $data);
187
    }
188
189
    /**
190
     * Method sends DELETE request to server
191
     *
192
     * @param string $endpoint
193
     *            Calling endpoint
194
     * @param array $data
195
     *            Request data
196
     * @return mixed Result of the request
197
     */
198
    public function sendDeleteRequest(string $endpoint, array $data = [])
199
    {
200
        return $this->sendFormRequest('DELETE', $endpoint, $data);
201
    }
202
203
    /**
204
     * Method sends GET request to server.
205
     *
206
     * @param string $endpoint
207
     *            Calling endpoint.
208
     * @return mixed Result of the remote call.
209
     */
210
    public function sendGetRequest(string $endpoint)
211
    {
212
        $fullUrl = $this->url . '/' . ltrim($endpoint, '/');
213
214
        $fullUrl = str_replace(' ', '%20', $fullUrl);
215
216
        list ($body, $code) = $this->sendRequest($fullUrl, $this->getCommonHeaders(), 'GET');
217
218
        return $this->dispatchResult($fullUrl, $code, $body);
219
    }
220
221
    /**
222
     * Method sets idempotence key.
223
     * To remove the key just call this method the second time with the '' parameter
224
     *
225
     * @param string $key
226
     *            Idempotence key
227
     */
228
    public function setIdempotencyKey(string $key): void
229
    {
230
        $this->idempotencyKey = $key;
231
    }
232
233
    /**
234
     * Method returns idempotency key
235
     *
236
     * @return string Idempotency key
237
     */
238
    public function getIdempotencyKey(): string
239
    {
240
        return $this->idempotencyKey;
241
    }
242
243
    /**
244
     * Method returns URL
245
     *
246
     * @return string URL
247
     */
248
    public function getUrl(): string
249
    {
250
        return $this->url;
251
    }
252
253
    /**
254
     * Method returns headers
255
     *
256
     * @return array Headers
257
     */
258
    public function getHeaders(): array
259
    {
260
        return $this->headers;
261
    }
262
}
263