generated from Firehed/php-library-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
188 lines (167 loc) · 5.91 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
<?php
declare(strict_types=1);
namespace SnapAuth;
use Composer\InstalledVersions;
use JsonException;
use SensitiveParameter;
use function assert;
use function curl_close;
use function curl_errno;
use function curl_exec;
use function curl_getinfo;
use function curl_init;
use function curl_setopt_array;
use function curl_version;
use function is_array;
use function is_string;
use function json_decode;
use function json_encode;
use function sprintf;
use function strlen;
use const CURLE_OK;
use const CURLINFO_RESPONSE_CODE;
use const CURLOPT_HTTPHEADER;
use const CURLOPT_POST;
use const CURLOPT_POSTFIELDS;
use const CURLOPT_RETURNTRANSFER;
use const CURLOPT_URL;
use const JSON_THROW_ON_ERROR;
/**
* SDK Prototype. This makes no attempt to short-circuit the network for
* internal use, forcing a completely dogfooded experience.
*
* TODO: make testable, presumably via PSR-18
* TODO: make an interface so the entire client can be mocked by developers
*/
class Client
{
private const DEFAULT_API_HOST = 'https://api.snapauth.app';
private string $secretKey;
public function __construct(
#[SensitiveParameter] ?string $secretKey = null,
private string $apiHost = self::DEFAULT_API_HOST,
) {
// Auto-detect if not provided
if ($secretKey === null) {
$env = getenv('SNAPAUTH_SECRET_KEY');
if ($env === false) {
throw new Exception\MissingSecretKey();
}
$secretKey = $env;
}
if (!str_starts_with($secretKey, 'secret_')) {
throw new Exception\InvalidSecretKey();
}
$this->secretKey = $secretKey;
}
public function verifyAuthToken(string $authToken): AuthResponse
{
return new AuthResponse($this->makeApiCall(
route: '/auth/verify',
params: [
'token' => $authToken,
]
));
}
/**
* @param array{
* username?: string,
* id: string,
* } $user
*/
public function attachRegistration(string $regToken, array $user): Credential
{
return new Credential($this->makeApiCall(
route: '/credential/create',
params: [
'token' => $regToken,
'user' => $user,
]
));
}
/**
* @internal This method is made public for cases where APIs do not have
* native SDK support, but is NOT considered part of the public, stable
* API and is not subject to SemVer.
*
* @param mixed[] $params
* @return mixed[]
*/
public function makeApiCall(string $route, array $params): array
{
// TODO: PSR-xx
$json = json_encode($params, JSON_THROW_ON_ERROR);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => sprintf('%s%s', $this->apiHost, $route),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode(':' . $this->secretKey),
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
sprintf(
'User-Agent: php-sdk/%s curl/%s php/%s',
InstalledVersions::getVersion('snapauth/sdk'),
curl_version()['version'] ?? 'unknown',
PHP_VERSION,
),
sprintf('X-SDK: php/%s', InstalledVersions::getVersion('snapauth/sdk')),
],
]);
try {
$response = curl_exec($ch);
$errno = curl_errno($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($response === false || $errno !== CURLE_OK) {
throw new Exception\Network($errno);
}
} finally {
curl_close($ch);
}
assert(is_string($response), 'No response body despite CURLOPT_RETURNTRANSFER');
try {
$decoded = json_decode($response, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
// Received non-JSON response - wrap and rethrow
throw new Exception\MalformedResponse('Received non-JSON response', $code);
}
if (!is_array($decoded) || !array_key_exists('result', $decoded)) {
// Received JSON response in an unexpected format
throw new Exception\MalformedResponse('Received JSON in an unexpected format', $code);
}
// Success!
if ($decoded['result'] !== null) {
assert($code >= 200 && $code < 300, 'Got a result with a non-2xx response');
return $decoded['result'];
}
// The `null` result indicated an error. Parse out the response shape
// more and throw an appropriate ApiError.
if (!array_key_exists('errors', $decoded)) {
throw new Exception\MalformedResponse('Error details missing', $code);
}
$errors = $decoded['errors'];
if (!is_array($errors) || !array_is_list($errors) || count($errors) === 0) {
throw new Exception\MalformedResponse('Error details are invalid or empty', $code);
}
$primaryError = $errors[0];
if (
!is_array($primaryError)
|| !array_key_exists('code', $primaryError)
|| !array_key_exists('message', $primaryError)
) {
throw new Exception\MalformedResponse('Error details are invalid or empty', $code);
}
// Finally, the error details are known to be in the correct shape.
throw new Exception\CodedError($primaryError['message'], $primaryError['code'], $code);
}
public function __debugInfo(): array
{
return [
'apiHost' => $this->apiHost,
'secretKey' => substr($this->secretKey, 0, 9) . '***' . substr($this->secretKey, -2),
];
}
}