-
Notifications
You must be signed in to change notification settings - Fork 86
/
Client.php
457 lines (395 loc) · 12.5 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<?php
declare(strict_types=1);
/*
* Copyright (C) 2013 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailjet;
use Mailjet\Normalizer\NormalizerInterface;
class Client
{
public const WRAPPER_VERSION = Config::WRAPPER_VERSION;
/**
* connect_timeout: (float, default=2) Float describing the number of
* seconds to wait while trying to connect to a server. Use 0 to wait
* indefinitely (the default behavior).
*/
public const CONNECT_TIMEOUT = 'connect_timeout';
/**
* timeout: (float, default=15) Float describing the timeout of the
* request in seconds. Use 0 to wait indefinitely (the default behavior).
*/
public const TIMEOUT = 'timeout';
/**
* proxy: (array, default=none) Array describing the proxy options used by guzzle client
* See guzzle-http for specification.
*/
public const PROXY = 'proxy';
private $apikey;
private $apisecret;
private $apitoken;
private $version = Config::MAIN_VERSION;
private $url = Config::MAIN_URL;
private $secure = Config::SECURED;
private $call = true;
private $settings = [];
private $changed = false;
/**
* @var int[]
*/
private $requestOptions = [
self::TIMEOUT => 15,
self::CONNECT_TIMEOUT => 2,
];
/**
* @var string[]
*/
private $smsResources = [
'send',
'sms',
'sms-send',
];
/**
* @var string[]
*/
private $dataAction = [
'csverror/text:csv',
'csvdata/text:plain',
'JSONError/application:json/LAST',
];
/**
* Client constructor requires:.
*
* @param string $key Mailjet API Key
* @param string|null $secret Mailjet API Secret
* @param bool $call performs the call or not
* @param array $settings
*/
public function __construct(string $key, string $secret = null, bool $call = true, array $settings = [])
{
$this->setAuthentication($key, $secret, $call, $settings);
}
/**
* Trigger a POST request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function post(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('POST', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a GET request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function get(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('GET', $resource[0], $resource[1], $args);
if (isset($resource['normalizer']) && class_exists($resource['normalizer'])) {
/**
* @var $normalizer NormalizerInterface
*/
$normalizer = $resource['normalizer'];
if ($normalizer::shouldBeNormalized($args)) {
$result = $normalizer::normalizeResponse($result);
}
}
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a PUT request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function put(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('PUT', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Trigger a DELETE request.
*
* @param array $resource Mailjet Resource/Action pair
* @param array $args Request arguments
* @param array $options
* @return Response
*/
public function delete(array $resource, array $args = [], array $options = []): Response
{
if (!empty($options)) {
$this->setOptions($options, $resource);
}
$result = $this->_call('DELETE', $resource[0], $resource[1], $args);
if (!empty($this->changed)) {
$this->setSettings();
}
return $result;
}
/**
* Sets if we need to use https or http protocol while using API Url.
*
* @param bool|mixed $bIsSecured True use https / false use http
* @return bool true if we set value false otherwise
*/
public function setSecureProtocol($bIsSecured = null): bool
{
if (\is_bool($bIsSecured)) {
$this->secure = $bIsSecured;
return true;
}
return false;
}
/**
* Set HTTP request Timeout.
*
* @param int $timeout
*/
public function setTimeout(int $timeout): void
{
$this->requestOptions[self::TIMEOUT] = $timeout;
}
/**
* Set HTTP proxy options
* See: http://docs.guzzlephp.org/en/stable/request-options.html#proxy.
*
* @param array $proxyArray
*/
public function setHttpProxy(array $proxyArray): void
{
$this->requestOptions[self::PROXY] = $proxyArray;
}
/**
* Set HTTP connection Timeout.
*
* @param int $timeout
*/
public function setConnectionTimeout(int $timeout): void
{
$this->requestOptions[self::CONNECT_TIMEOUT] = $timeout;
}
/**
* Get HTTP request Timeout
* $return int|null.
*/
public function getTimeout(): ?int
{
return $this->requestOptions[self::TIMEOUT];
}
/**
* Get HTTP connection Timeout
* $return int|null.
*/
public function getConnectionTimeout(): ?int
{
return $this->requestOptions[self::CONNECT_TIMEOUT];
}
/**
* Add a HTTP request option.
*
* @param string $key
* @param mixed $value
* [IMPORTANT]Default options will be overwritten
* if such option is provided
* @see \GuzzleHttp\RequestOptions for a list of available request options.
*/
public function addRequestOption(string $key, $value): void
{
if ($key && (null !== $value)) {
$this->requestOptions[$key] = $value;
}
}
/**
* Get HTTP connection options
* $return array.
*/
public function getRequestOptions(): array
{
return $this->requestOptions;
}
/**
* Set auth.
*
* @param string $key
* @param string|null $secret
* @param bool $call
* @param array $settings
*/
public function setAuthentication(string $key, ?string $secret, bool $call, array $settings = []): void
{
$isBasicAuth = $this->isBasicAuthentication($key, $secret);
if ($isBasicAuth) {
$this->apikey = $key;
$this->apisecret = $secret;
} else {
$this->apitoken = $key;
$this->version = Config::SMS_VERSION;
}
$this->initSettings($call, $settings);
$this->setSettings();
}
// phpcs:disable
/**
* Magic method to call a mailjet resource.
* @param string $method Http method
* @param string $resource mailjet resource
* @param string $action mailjet resource action
* @param array $args Request arguments
* @return Response server response
*/
private function _call(string $method, string $resource, string $action, array $args): Response
{
$args = array_merge([
'id' => '',
'actionid' => '',
'filters' => [],
'body' => 'GET' === $method ? null : '{}',
], array_change_key_case($args));
$url = $this->buildURL($resource, $action, (string)$args['id'], $args['actionid']);
$contentType = 'application/json';
if ('csvdata/text:plain' === $action) {
$contentType = 'text/plain';
} elseif ('csverror/text:csv' === $action) {
$contentType = 'text/csv';
}
$isBasicAuth = $this->isBasicAuthentication($this->apikey, $this->apisecret);
$auth = $isBasicAuth ? [$this->apikey, $this->apisecret] : [$this->apitoken];
$request = new Request(
$auth,
$method,
$url,
$args['filters'],
$args['body'],
$contentType,
$this->requestOptions
);
return $request->call($this->call);
}
// phpcs:enable
/**
* Build the base API url depending on wether user need a secure connection
* or not.
*
* @return string the API url;
*/
private function getApiUrl(): string
{
$h = true === $this->secure ? 'https' : 'http';
return sprintf('%s://%s/%s/', $h, $this->url, $this->version);
}
/**
* Checks that both parameters are strings, which means
* that basic authentication will be required.
*
* @param mixed $key
* @param mixed $secret
* @return bool flag
*/
private function isBasicAuthentication($key, $secret): bool
{
return !empty($key) && !empty($secret);
}
/**
* Build the final call url without query strings.
*
* @param string $resource Mailjet resource
* @param string $action Mailjet resource action
* @param string $id mailjet resource id
* @param string $actionid mailjet resource actionid
* @return string final call url
*/
private function buildURL(string $resource, string $action, string $id, string $actionid): string
{
$path = 'REST';
if (\in_array($resource, $this->smsResources, true)) {
$path = '';
} elseif (\in_array($action, $this->dataAction, true)) {
$path = 'DATA';
} elseif ('v4' === $this->version) {
$path = '';
}
$arrayFilter = [$path, $resource, $id, $action, $actionid];
return $this->getApiUrl() . implode('/', array_filter($arrayFilter));
}
/**
* Temporary set the variables generating the url.
*
* @param array $options contain temporary modifications for the client
* @param array $resource may contain the version linked to the resource
*/
private function setOptions(array $options, array $resource): void
{
if (isset($options['version'])) {
$this->version = $options['version'];
} elseif (isset($resource[2])) {
$this->version = $resource[2];
}
$this->url = (string)($options['url'] ?? Config::MAIN_URL);
$this->secure = $options['secured'] ?? Config::SECURED;
$this->call = $options['call'] ?? true;
$this->changed = true;
}
/**
* set back the variables generating the url.
*/
private function setSettings(): void
{
if (!empty($this->settings['url']) && \is_string($this->settings['url'])) {
$this->url = $this->settings['url'];
}
if (!empty($this->settings['version']) && \is_string($this->settings['version'])) {
$this->version = $this->settings['version'];
}
if (isset($this->settings['call']) && \is_bool($this->settings['call'])) {
$this->call = $this->settings['call'];
}
if (isset($this->settings['secured']) && \is_bool($this->settings['secured'])) {
$this->secure = $this->settings['secured'];
}
$this->changed = false;
}
/**
* Set a backup if the variables generating the url are change during a call.
*
* @param bool $call
* @param array $settings
*/
private function initSettings(bool $call, array $settings = []): void
{
$this->settings['url'] = $settings['url'] ?? $this->url;
$this->settings['version'] = $settings['version'] ?? $this->version;
$this->settings['call'] = $call;
$this->settings['secured'] = $settings['secured'] ?? $this->secure;
$this->changed = false;
}
}