-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClient.php
More file actions
66 lines (55 loc) · 1.88 KB
/
HttpClient.php
File metadata and controls
66 lines (55 loc) · 1.88 KB
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
<?php
namespace Lettermint\Client;
use Composer\InstalledVersions;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class HttpClient
{
private string $apiToken;
private string $baseUrl;
private Client $client;
public function __construct(string $apiToken, string $baseUrl)
{
$this->apiToken = $apiToken;
$this->baseUrl = rtrim($baseUrl, '/');
$this->client = new Client([
'base_uri' => $this->baseUrl,
'timeout' => 15,
'headers' => [
'Content-Type' => 'application/json',
'x-lettermint-token' => $this->apiToken,
'User-Agent' => sprintf(
'Lettermint/%s (PHP; PHP %s)',
InstalledVersions::getPrettyVersion('lettermint/lettermint-php') ?? 'unknown',
PHP_VERSION
),
],
]);
}
/**
* Fluent-style usage with dedicated endpoints (builder pattern)
*
* @param array $headers Additional headers for this request
* @return array Resulting API response
*
* @throws \Exception On HTTP or decode failure
*/
public function post(string $path, array $data, array $headers = []): array
{
try {
$requestOptions = ['json' => $data];
if (! empty($headers)) {
$requestOptions['headers'] = $headers;
}
$response = $this->client->post($path, $requestOptions);
$body = $response->getBody()->getContents();
$result = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('Could not decode API response');
}
return $result;
} catch (GuzzleException $e) {
throw new \Exception('API request failed: '.$e->getMessage(), 0, $e);
}
}
}