forked from apisnetworks/apiscp-dns-vultr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Api.php
89 lines (78 loc) · 2.04 KB
/
Api.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
<?php declare(strict_types=1);
/**
* Copyright (C) Apis Networks, Inc - All Rights Reserved.
*
* Unauthorized copying of this file, via any medium, is
* strictly prohibited without consent. Any dissemination of
* material herein is prohibited.
*
* For licensing inquiries email <licensing@apisnetworks.com>
*
* Written by Matt Saladna <matt@apisnetworks.com>, August 2018
*/
namespace Opcenter\Dns\Providers\Vultr;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Response;
class Api
{
protected const VULTR_ENDPOINT = 'https://api.vultr.com/v1/';
/**
* @var \GuzzleHttp\Client
*/
protected $client;
/**
* @var string
*/
protected $key;
/**
* @var Response
*/
protected $lastResponse;
/**
* Api constructor.
*
* @param string $key API key
*/
public function __construct(string $key)
{
$this->key = $key;
$this->client = new \GuzzleHttp\Client([
'base_uri' => static::VULTR_ENDPOINT,
]);
}
public function do(string $method, string $endpoint, array $params = []): array
{
$method = strtoupper($method);
if (!\in_array($method, ['GET', 'POST'])) {
error("Unknown method `%s'", $method);
return [];
}
if ($endpoint[0] === '/') {
warn("Stripping `/' from endpoint `%s'", $endpoint);
$endpoint = ltrim($endpoint, '/');
}
$paramKey = $method === 'POST' ? 'form_params' : 'query';
try {
$this->lastResponse = $this->client->request($method, $endpoint, [
'headers' => [
'User-Agent' => PANEL_BRAND . ' ' . APNSCP_VERSION,
'API-Key' => $this->key,
'Accept' => 'application/json'
],
$paramKey => $params
]);
} catch (ServerException $e) {
if ($e->getResponse()->getStatusCode() === 503) {
// 2 req/s is stupid.
usleep(500000);
return $this->do($method, $endpoint, $params);
}
throw $e;
}
return \json_decode($this->lastResponse->getBody()->getContents(), true) ?? [];
}
public function getResponse(): ?Response
{
return $this->lastResponse;
}
}