-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathClient.php
398 lines (345 loc) · 12.2 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
<?php
declare(strict_types = 1);
namespace DnsMadeEasy;
use DnsMadeEasy\Exceptions\Client\Http\BadRequestException;
use DnsMadeEasy\Exceptions\Client\Http\HttpException;
use DnsMadeEasy\Exceptions\Client\Http\NotFoundException;
use DnsMadeEasy\Exceptions\Client\ManagerNotFoundException;
use DnsMadeEasy\Interfaces\ClientInterface;
use DnsMadeEasy\Interfaces\Managers\AbstractManagerInterface;
use DnsMadeEasy\Interfaces\Managers\ContactListManagerInterface;
use DnsMadeEasy\Interfaces\Managers\FolderManagerInterface;
use DnsMadeEasy\Interfaces\Managers\ManagedDomainManagerInterface;
use DnsMadeEasy\Interfaces\Managers\RecordFailoverManagerInterface;
use DnsMadeEasy\Interfaces\Managers\SecondaryDomainManagerInterface;
use DnsMadeEasy\Interfaces\Managers\SecondaryIPSetManagerInterface;
use DnsMadeEasy\Interfaces\Managers\SOARecordManagerInterface;
use DnsMadeEasy\Interfaces\Managers\TemplateManagerInterface;
use DnsMadeEasy\Interfaces\Managers\TransferAclManagerInterface;
use DnsMadeEasy\Interfaces\Managers\UsageManagerInterface;
use DnsMadeEasy\Interfaces\Managers\VanityNameServerManagerInterface;
use DnsMadeEasy\Interfaces\PaginatorFactoryInterface;
use DnsMadeEasy\Managers\ContactListManager;
use DnsMadeEasy\Managers\FolderManager;
use DnsMadeEasy\Managers\ManagedDomainManager;
use DnsMadeEasy\Managers\RecordFailoverManager;
use DnsMadeEasy\Managers\SecondaryDomainManager;
use DnsMadeEasy\Managers\SecondaryIPSetManager;
use DnsMadeEasy\Managers\SOARecordManager;
use DnsMadeEasy\Managers\TemplateManager;
use DnsMadeEasy\Managers\TransferAclManager;
use DnsMadeEasy\Managers\UsageManager;
use DnsMadeEasy\Managers\VanityNameServerManager;
use DnsMadeEasy\Pagination\Factories\PaginatorFactory;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* DNS Made Easy API Client SDK.
*
* @package DnsMadeEasy
*
* @property-read ContactListManagerInterface $contactlists
* @property-read FolderManagerInterface $folders
* @property-read ManagedDomainManagerInterface $domains
* @property-read VanityNameServerManagerInterface $vanity
* @property-read TemplateManagerInterface $templates
* @property-read TransferAclManagerInterface $transferacls
* @property-read SOARecordManagerInterface $soarecords
* @property-read UsageManagerInterface $usage
* @property-read SecondaryIPSetManagerInterface $secondaryipsets;
* @property-read SecondaryDomainManagerInterface $secondarydomains;
* @property-read RecordFailoverManagerInterface $failover;
*/
class Client implements ClientInterface, LoggerAwareInterface
{
/**
* Logger interface to use for log messages.
*
* @var LoggerInterface|NullLogger
*/
public LoggerInterface $logger;
protected HttpClient $client;
/**
* The DNS Made Easy API Key.
*/
protected string $apiKey;
/**
* The DNS Made Easy Secret Key.
*/
protected string $secretKey;
/**
* The DNS Made Easy API Endpoint.
*/
protected string $endpoint = 'https://api.dnsmadeeasy.com/V2.0';
/**
* The pagination factory to use for paginated resource collections.
*
* @var PaginatorFactoryInterface|PaginatorFactory
*/
protected PaginatorFactoryInterface $paginatorFactory;
/**
* A cache of instantiated manager classes.
*
* @var mixed[]
*/
protected array $managers = [];
/**
* A map of manager names to classes.
*
* @var string[]
*/
protected array $managerMap = [
'contactlists' => ContactListManager::class,
'domains' => ManagedDomainManager::class,
'folders' => FolderManager::class,
'vanity' => VanityNameServerManager::class,
'templates' => TemplateManager::class,
'transferacls' => TransferAclManager::class,
'soarecords' => SOARecordManager::class,
'secondaryipsets' => SecondaryIPSetManager::class,
'secondarydomains' => SecondaryDomainManager::class,
'failover' => RecordFailoverManager::class,
];
/**
* The ID of the last request to the API.
*/
protected ?string $requestId = null;
/**
* The request limit on the API.
*/
protected ?int $requestLimit = null;
/**
* The number of requests remaining until the limit is hit.
*/
protected ?int $requestsRemaining = null;
public function __construct(?HttpClient $client = null, ?PaginatorFactoryInterface $paginatorFactory = null, ?LoggerInterface $logger = null)
{
// If we weren't given a HTTP client, create a new Guzzle client.
if ($client === null) {
$client = new HttpClient();
}
// If we don't have a paginator factory, use our own.
if ($paginatorFactory === null) {
$this->paginatorFactory = new PaginatorFactory();
}
$this->setHttpClient($client);
// If we don't have a logger, use the null logger.
if ($logger === null) {
$logger = new NullLogger();
}
$this->logger = $logger;
}
public function __get(string $name): mixed
{
// Usage is a special manager and not like the others.
if ($name === 'usage') {
if (! isset($this->managers['usage'])) {
$this->managers['usage'] = new UsageManager($this);
}
return $this->managers['usage'];
}
return $this->getManager($name);
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
public function setHttpClient(HttpClient $client): self
{
$this->client = $client;
return $this;
}
public function getHttpClient(): HttpClient
{
return $this->client;
}
public function setEndpoint(string $endpoint): self
{
$this->endpoint = $endpoint;
return $this;
}
public function getEndpoint(): string
{
return $this->endpoint;
}
public function setApiKey(string $key): self
{
$this->apiKey = $key;
return $this;
}
public function getApiKey(): string
{
return $this->apiKey;
}
public function setSecretKey(string $key): self
{
$this->secretKey = $key;
return $this;
}
public function getSecretKey(): string
{
return $this->secretKey;
}
public function setPaginatorFactory(PaginatorFactoryInterface $factory): self
{
$this->paginatorFactory = $factory;
return $this;
}
public function getPaginatorFactory(): PaginatorFactoryInterface
{
return $this->paginatorFactory;
}
public function get(string $url, ?array $params = null): ResponseInterface
{
$queryString = '';
if ($params !== null) {
$queryString = '?' . http_build_query($params);
}
$url .= $queryString;
$request = new Request('GET', $this->endpoint . $url);
return $this->send($request);
}
public function post(string $url, mixed $payload): ResponseInterface
{
$request = new Request('POST', $this->endpoint . $url, [], 'php://temp');
$request->withHeader('Content-Type', 'application/json');
$request->getBody()->write(json_encode($payload, JSON_THROW_ON_ERROR));
return $this->send($request);
}
public function put(string $url, mixed $payload): ResponseInterface
{
$request = new Request('PUT', $this->endpoint . $url, [], 'php://temp');
$request->withHeader('Content-Type', 'application/json');
$request->getBody()->write(json_encode($payload, JSON_THROW_ON_ERROR));
return $this->send($request);
}
public function delete(string $url, mixed $payload = null): ResponseInterface
{
$request = new Request('DELETE', $this->endpoint . $url);
if ($payload !== null) {
$request->withHeader('Content-Type', 'application/json');
$request->getBody()->write(json_encode($payload, JSON_THROW_ON_ERROR));
}
return $this->send($request);
}
public function send(RequestInterface $request): ResponseInterface
{
$this->logger->debug("[DnsMadeEasy] API Request: {$request->getMethod()} {$request->getUri()}");
$request = $request->withHeader('Accept', 'application/json');
$request = $this->addAuthHeaders($request);
$response = $this->client->send($request, [RequestOptions::HTTP_ERRORS => false]);
$this->logger->debug("[DnsMadeEasy] API Response: {$response->getStatusCode()} {$response->getReasonPhrase()}");
$this->updateLimits($response);
$statusCode = $response->getStatusCode();
if ((int) substr((string) $statusCode, 0, 1) <= 3) {
return $response;
}
$lookup = [
400 => BadRequestException::class,
404 => NotFoundException::class,
];
if (array_key_exists($statusCode, $lookup)) {
$exceptionClass = $lookup[$statusCode];
} else {
$exceptionClass = HttpException::class;
}
$exception = new $exceptionClass($response->getReasonPhrase(), $statusCode);
$exception->setRequest($request);
$exception->setResponse($response);
throw $exception;
}
/**
* Return the ID of the last API request.
*/
public function getLastRequestId(): ?string
{
return $this->requestId;
}
/**
* Get the request limit.
*/
public function getRequestLimit(): ?int
{
return $this->requestLimit;
}
/**
* Get the number of requests remaining before you hit the request limit.
*/
public function getRequestsRemaining(): ?int
{
return $this->requestsRemaining;
}
/**
* Fetch the API request details from the last API response.
*/
protected function updateLimits(ResponseInterface $response): void
{
$requestId = current($response->getHeader('x-dnsme-requestId'));
if ($requestId === false) {
$this->requestId = null;
} else {
$this->requestId = $requestId;
}
$requestsRemaining = current($response->getHeader('x-dnsme-requestsRemaining'));
if ($requestsRemaining === false) {
$this->requestsRemaining = null;
} else {
$this->requestsRemaining = (int) $requestsRemaining;
}
$requestLimit = current($response->getHeader('x-dnsme-requestLimit'));
if ($requestLimit === false) {
$this->requestLimit = null;
} else {
$this->requestLimit = (int) $requestLimit;
}
}
/**
* Adds auth headers to requests. These are generated based on the Api Key and the Secret Key.
*
* @throws \Exception
*/
protected function addAuthHeaders(RequestInterface $request): RequestInterface
{
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$timestamp = $now->format('r');
$hmac = hash_hmac('sha1', $timestamp, $this->getSecretKey());
$request = $request->withHeader('x-dnsme-apiKey', $this->getApiKey());
$request = $request->withHeader('x-dnsme-requestDate', $timestamp);
$request = $request->withHeader('x-dnsme-hmac', $hmac);
return $request;
}
/**
* Check if a manager exists with that name in our manager map.
*/
protected function hasManager(string $name): bool
{
$name = strtolower($name);
return array_key_exists($name, $this->managerMap);
}
/**
* Gets the manager with the specified name.
*
* @throws ManagerNotFoundException
*/
protected function getManager(string $name): AbstractManagerInterface
{
if (! $this->hasManager($name)) {
throw new ManagerNotFoundException();
}
$name = strtolower($name);
if (! isset($this->managers[$name])) {
$this->managers[$name] = new $this->managerMap[$name]($this);
}
return $this->managers[$name];
}
}