-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpClient.php
399 lines (345 loc) · 11.9 KB
/
HttpClient.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
<?php
declare(strict_types=1);
namespace Darwin;
use Darwin\Models\Client as ClientModel;
use Darwin\Models\Country;
use Darwin\Models\MarketingSource;
use Psl\Type as T;
use Psr\Clock\ClockInterface;
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 RuntimeException;
use SensitiveParameter;
use Throwable;
use Webmozart\Assert\Assert;
use function get_debug_type;
use function hash_hmac;
use function hash_hmac_algos;
use function in_array;
use function is_array;
use function is_numeric;
use function is_string;
use function json_decode;
use function json_encode;
use function sprintf;
use function trim;
use const JSON_THROW_ON_ERROR;
/**
* @psalm-type AuthPayload = array{
* companyid: int,
* timestamp: int,
* APIMethod: non-empty-string,
* hash_hmac: non-empty-string,
* }
*/
final class HttpClient implements Client
{
private RequestInterface|null $lastRequest = null;
private ResponseInterface|null $lastResponse = null;
public function __construct(
private readonly string $serverUrl,
private readonly string $basePath,
#[SensitiveParameter]
private readonly string $sharedSecret,
private readonly int $companyId,
private readonly ClockInterface $clock,
private readonly ClientInterface $httpClient,
private readonly RequestFactoryInterface $requestFactory,
private readonly StreamFactoryInterface $streamFactory,
) {
}
/** @return list<Country> */
public function listCountries(): array
{
$request = $this->createRequest(
'POST',
'getCountryList',
'search',
[],
);
$payload = $this->sendRequest($request);
$list = $payload['CountryList'] ?? null;
if (! is_array($list)) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
'The country list is not an array',
);
}
$type = T\shape([
'id' => T\positive_int(),
// Non-empty-string will be unwise here. It is very likely that there are many countries with empty names.
'countryname' => T\string(),
], true);
$data = [];
foreach ($list as $item) {
if (! is_array($item)) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
'The list of countries contained a non-array member',
);
}
$value = $type->coerce($item);
if ($value['countryname'] === '') {
continue;
}
$data[] = new Country($value['id'], $value['countryname']);
}
return $data;
}
public function findClientByEmailAddress(string $emailAddress): ClientModel|null
{
$request = $this->createRequest(
'POST',
'getClient',
'search',
['email' => $emailAddress],
);
try {
$payload = $this->sendRequest($request);
} catch (RequestFailed $e) {
if ($e->getCode() === 404) {
return null;
}
throw $e;
}
$clientArray = $payload['Client'] ?? null;
if (! is_array($clientArray)) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
sprintf(
'Expected an array representing the client information but received "%s"',
get_debug_type($clientArray),
),
);
}
return $this->hydrateClient($clientArray);
}
/** @inheritDoc */
public function createOrUpdateClientWithEmailAddress(string $emailAddress, array $clientData): int
{
$clientData['email'] = $emailAddress;
$request = $this->createRequest(
'POST',
'createClient',
'client',
$clientData,
);
$payload = $this->sendRequest($request);
if (! isset($payload['clientid']) || ! is_numeric($payload['clientid'])) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
'The `createClient` response payload should contain a client identifier in the field '
. '`clientid` but none was found',
);
}
return (int) $payload['clientid'];
}
/** @inheritDoc */
public function createEnquiry(int $clientId, array $payload): int
{
$payload['clientid'] = $clientId;
$request = $this->createRequest(
'POST',
'createTripEnquiry',
'tripenquiry',
$payload,
);
$payload = $this->sendRequest($request);
if (! isset($payload['tripid']) || ! is_numeric($payload['tripid'])) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
'The `createEnquiry` response payload should contain a trip identifier in the field '
. '`tripid` but none was found',
);
}
return (int) $payload['tripid'];
}
/** @inheritDoc */
public function getMarketingSourceCodes(): array
{
$request = $this->createRequest(
'POST',
'getMarketingSourceCodes',
null,
null,
);
$payload = $this->sendRequest($request);
$list = $payload['SourceList'] ?? null;
if (! is_array($list)) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
'The marketing source codes list should contain a top-level key of `SourceList`',
);
}
$type = T\shape([
'id' => T\positive_int(),
'subsource' => T\string(),
'sourcecatid' => T\positive_int(),
'sourcecat' => T\non_empty_string(),
'isactive' => T\union(T\literal_scalar(1), T\literal_scalar(0)),
'ispublic' => T\union(T\literal_scalar(1), T\literal_scalar(0)),
], true);
$data = [];
foreach ($list as $item) {
if (! is_array($item)) {
throw new UnexpectedAPIPayload(
$request,
T\instance_of(ResponseInterface::class)->assert($this->lastResponse),
'The list of marketing source codes contained a non-array member',
);
}
$value = $type->coerce($item);
$data[] = new MarketingSource(
$value['id'],
$value['subsource'],
$value['sourcecatid'],
$value['sourcecat'],
$value['isactive'] === 1,
$value['ispublic'] === 1,
);
}
return $data;
}
/** @return array<string, mixed> */
private function sendRequest(RequestInterface $request): array
{
$this->lastRequest = $request;
try {
$response = $this->httpClient->sendRequest($request);
$this->lastResponse = $response;
} catch (Throwable $e) {
throw RequestFailed::becauseOfAnIoError($request, $e);
}
$body = (string) $response->getBody();
if ($body === '') {
throw new UnexpectedAPIPayload($request, $response, 'The response body was empty');
}
if ($response->getStatusCode() === 404) {
throw RequestFailed::becauseItWasA404($request, $response);
}
// This "API" returns JSON strings exclusively
try {
/** @psalm-suppress MixedAssignment */
$body = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
Assert::isArray($body);
} catch (Throwable $e) {
throw RequestFailed::becauseTheResponseBodyWasNotValidJson($request, $response, $e);
}
/** @psalm-var mixed $result */
$result = $body['Result'] ?? null;
/** @psalm-var mixed $code */
$code = $body['Code'] ?? null;
/** @psalm-var mixed $message */
$message = $body['Msg'] ?? null;
if ((int) $code !== 200 || $result !== 'Success') {
throw RequestFailed::withErrorResult($request, $response, (string) $message, (int) $code);
}
Assert::isMap($body);
return $body;
}
/**
* @param non-empty-string $httpMethod
* @param non-empty-string $methodName
* @param non-empty-string|null $payloadKey
* @param array<string, mixed>|null $payload
*/
private function createRequest(
string $httpMethod,
string $methodName,
string|null $payloadKey,
array|null $payload,
): RequestInterface {
$uri = sprintf(
'%s/%s/%s.php',
trim($this->serverUrl, '/'),
trim($this->basePath, '/'),
$methodName,
);
$body = json_encode($this->prepareBodyPayload(
$methodName,
$payloadKey,
$payload,
), JSON_THROW_ON_ERROR);
return $this->requestFactory->createRequest($httpMethod, $uri)
->withHeader('Content-Type', 'application/json; charset=utf-8')
->withBody($this->streamFactory->createStream(
$body,
));
}
/**
* @param non-empty-string $methodName
* @param non-empty-string|null $payloadKey
* @param array<string, mixed>|null $payload
*
* @return array{auth: AuthPayload}&array<string, array>
*/
private function prepareBodyPayload(string $methodName, string|null $payloadKey, array|null $payload): array
{
$value = [
'auth' => $this->authPayload($methodName),
];
if (is_string($payloadKey) && is_array($payload)) {
$value[$payloadKey] = $payload;
}
return $value;
}
/**
* @param non-empty-string $methodName
*
* @return AuthPayload
*/
private function authPayload(string $methodName): array
{
if (! in_array('sha256', hash_hmac_algos())) {
throw new RuntimeException('SHA256 is not a supported hash algo on this machine');
}
// Timestamp is Unix time with ms
$timestamp = $this->clock->now()->getTimestamp() * 1000;
return [
'companyid' => $this->companyId,
'timestamp' => $timestamp,
'APIMethod' => $methodName,
'hash_hmac' => hash_hmac('sha256', sprintf(
'%d!%s!%d',
$this->companyId,
$methodName,
$timestamp,
), $this->sharedSecret, false),
];
}
/** @param array<array-key, mixed> $data */
private function hydrateClient(array $data): ClientModel
{
$id = $data['clientid'] ?? null;
$email = $data['email'] ?? null;
$first = $data['firstname'] ?? null;
$last = $data['lastname'] ?? null;
Assert::numeric($id);
Assert::nullOrStringNotEmpty($email);
Assert::nullOrString($first);
Assert::nullOrString($last);
return new ClientModel(
(int) $id,
(string) $email,
(string) $first,
(string) $last,
);
}
public function lastRequest(): RequestInterface|null
{
return $this->lastRequest;
}
public function lastResponse(): ResponseInterface|null
{
return $this->lastResponse;
}
}