-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
337 lines (300 loc) · 8.45 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
<?php declare(strict_types=1);
namespace Stefna\Mailchimp;
use InvalidArgumentException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Stefna\Mailchimp\Api\Campaigns\Campaigns as CampaignsApi;
use Stefna\Mailchimp\Api\Lists\Lists as ListsApi;
use Stefna\Mailchimp\Api\Templates\Templates;
use Stefna\Mailchimp\Exceptions\NotFoundException;
class Client
{
private const DEFAULT_ENDPOINT = 'https://<dc>.api.mailchimp.com/3.0';
protected ?LoggerInterface $logger = null;
protected ?ResponseInterface $lastResponse = null;
protected ?RequestInterface $lastRequest = null;
protected string $apiEndpoint = '';
public function __construct(
protected ClientInterface $httpClient,
protected string $apiKey,
protected RequestFactoryInterface $requestFactory,
protected UriFactoryInterface $uriFactory,
protected StreamFactoryInterface $streamFactory,
?string $apiEndpoint = null,
) {
$this->apiEndpoint = $apiEndpoint ?: $this->createApiEndpoint($apiKey);
}
public function lists(): ListsApi
{
return new ListsApi($this);
}
public function campaigns(): CampaignsApi
{
return new CampaignsApi($this);
}
public function templates(): Templates
{
return new Templates($this);
}
public function getLogger(): ?LoggerInterface
{
return $this->logger;
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function getHttpClient(): ClientInterface
{
return $this->httpClient;
}
/**
* @param array<string,string> $args
* @return array<string, mixed>
*/
public function get(string $path, array $args = []): array
{
/** @var array<string, mixed> */
return $this->request($this->createRequest(
'GET',
$this->createUrl($path, $args),
$this->getDefaultHeaders(),
)) ?? [];
}
/**
* @param array<string, string> $args
*/
public function delete(string $path, array $args = []): bool
{
return $this->request($this->createRequest(
'DELETE',
$this->createUrl($path, $args),
$this->getDefaultHeaders(),
), true);
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>|null
*/
public function post(string $path, array $data = []): array|null
{
/** @var array<string, mixed> */
return $this->request($this->createRequest(
'POST',
$this->createUrl($path),
$this->getDefaultHeaders(),
(string)json_encode($data),
));
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
public function put(string $path, array $data = []): array
{
$ret = $this->request($this->createRequest(
'PUT',
$this->createUrl($path),
$this->getDefaultHeaders(),
(string)json_encode($data),
));
if ($ret === null) {
throw new NotFoundException('Put item not found: ' . $path);
}
/** @var array<string, mixed> */
return $ret;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
public function patch(string $path, array $data = []): array
{
$ret = $this->request($this->createRequest(
'PATCH',
$this->createUrl($path),
$this->getDefaultHeaders(),
(string)json_encode($data),
));
if ($ret === null) {
throw new NotFoundException('Patch item not found: ' . $path);
}
return $ret;
}
/**
* @phpstan-return ($noOutput is true ? bool : array<string, mixed>|null)
* @return bool|array<string, mixed>|null
*/
public function request(RequestInterface $request, bool $noOutput = false): bool|array|null
{
$this->lastRequest = $request;
$this->logger?->debug('Request created', [
'method' => $request->getMethod(),
'target' => $request->getRequestTarget(),
'protocol_version' => $request->getProtocolVersion(),
'host' => $request->hasHeader('host') ? $request->getUri()->getHost() : null,
]);
return !$noOutput
? $this->response($this->sendRequest($request))
: $this->noOutputResponse($this->sendRequest($request));
}
public function noOutputResponse(ResponseInterface $response): bool
{
$this->lastResponse = $response;
$status = $response->getStatusCode();
$this->logger?->debug('Response created without output', [
'headers' => json_encode($response->getHeaders()),
'status' => $status,
]);
if ($status > 299) {
if ($status != 404) {
$contents = $response->getBody()->getContents();
$ret = json_decode($contents, true);
if ($ret && is_array($ret) && $this->logger) {
$this->logger->alert($this->formatError($ret));
}
}
return false;
}
return true;
}
/**
* @return array<string, mixed>|null
*/
public function response(ResponseInterface $response): ?array
{
$this->lastResponse = $response;
$contents = $response->getBody()->getContents();
$status = $response->getStatusCode();
if ($contents === '' && $status >= 200 && $status < 300) {
return [];
}
/** @var array<string, mixed>|null $ret */
$ret = json_decode($contents, true);
$jsonLastError = json_last_error();
$jsonOk = JSON_ERROR_NONE === $jsonLastError;
if ($jsonOk && $ret && isset($ret['status']) && is_numeric($ret['status'])) {
$status = (int)$ret['status'];
}
$this->logger?->debug('Response created', [
'headers' => json_encode($response->getHeaders()),
'body' => $jsonOk ? $ret : $contents,
'jsonLastError' => $jsonLastError,
'status' => $status,
]);
if ($status === 404) {
return null;
}
if ($status > 299 && is_array($ret)) {
$errorMsg = $this->formatError($ret);
$this->logger?->alert($errorMsg);
$msg = 'Error from API';
if ($errorMsg && $errorMsg[0] !== '{') {
$msg .= ": $errorMsg";
}
throw new RuntimeException($msg, $status);
}
if (!$jsonOk || !is_array($ret)) {
$this->logger?->warning('Could not decode json response', [
'headers' => json_encode($response->getHeaders()),
'body' => $contents,
'jsonLastError' => $jsonLastError,
'status' => $status,
]);
throw new RuntimeException('Could not decode json response');
}
return $ret;
}
/**
* @return array<string, string>
*/
public function getDefaultHeaders(): array
{
return [
'Accept' => 'application/vnd.api+json',
'Content-Type' => 'application/vnd.api+json',
'Authorization' => 'apikey ' . $this->apiKey,
];
}
public function getLastResponse(): ?ResponseInterface
{
return $this->lastResponse;
}
public function getLastRequest(): ?RequestInterface
{
return $this->lastRequest;
}
protected function createApiEndpoint(string $apiKey): string
{
if (!str_contains($apiKey, '-')) {
throw new InvalidArgumentException("Invalid api key: $apiKey");
}
[, $dc] = explode('-', $apiKey);
return (string)str_replace('<dc>', $dc, self::DEFAULT_ENDPOINT);
}
protected function sendRequest(RequestInterface $request): ResponseInterface
{
/** @noinspection PhpUnhandledExceptionInspection */
return $this->httpClient->sendRequest($request);
}
/**
* @param array<string,mixed> $data
*/
protected function formatError(array $data): string
{
if (!isset($data['title'])) {
return (string)json_encode($data);
}
$ret = is_string($data['title']) ? $data['title'] : '';
if (isset($data['errors']) && is_array($data['errors'])) {
$errors = [];
/** @var array<string, string> $error */
foreach ($data['errors'] as $error) {
if (is_array($error) && isset($error['field'], $error['message'])) {
$errors[] = " {$error['field']}: {$error['message']}";
}
}
$ret = "$ret\n" . implode("\n", $errors);
}
elseif (isset($data['detail']) && is_string($data['detail'])) {
$ret = $data['detail'];
}
return $ret;
}
/**
* @param array<string,string> $queryParams
*/
protected function createUrl(string $path, array $queryParams = []): UriInterface
{
$url = $this->apiEndpoint . '/' . $path;
if ($queryParams) {
$url .= '?' . http_build_query($queryParams);
}
return $this->uriFactory->createUri($url);
}
/**
* @param array<string, string|string[]> $headers
*/
protected function createRequest(
string $method,
UriInterface $uri,
array $headers = [],
?string $body = null,
): RequestInterface {
$ret = $this->requestFactory->createRequest($method, $uri);
foreach ($headers as $key => $value) {
$ret = $ret->withHeader($key, $value);
}
if ($body) {
$ret = $ret->withBody($this->streamFactory->createStream($body));
}
return $ret;
}
}