1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the africc/pdns-client library. |
5
|
|
|
* |
6
|
|
|
* (c) Gunter Grodotzki <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE file |
9
|
|
|
* that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace AfriCC\Pdns; |
13
|
|
|
|
14
|
|
|
use Exception; |
15
|
|
|
use AfriCC\Pdns\Endpoints\Endpointable; |
16
|
|
|
|
17
|
|
|
class Client |
18
|
|
|
{ |
19
|
|
|
protected $api_url; |
20
|
|
|
|
21
|
|
|
protected $api_key; |
22
|
|
|
|
23
|
|
|
public function __construct($api_url, $api_key) |
24
|
|
|
{ |
25
|
|
|
$this->api_url = (string) $api_url; |
26
|
|
|
|
27
|
|
|
$this->api_key = (string) $api_key; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function request(Endpointable $endpoint) |
31
|
|
|
{ |
32
|
|
|
$headers = [ |
33
|
|
|
'Accept: application/json', |
34
|
|
|
'X-API-Key: ' . $this->api_key, |
35
|
|
|
'Connection: close', |
36
|
|
|
]; |
37
|
|
|
|
38
|
|
|
if ($endpoint->getMethod() === 'POST') { |
39
|
|
|
$headers[] = 'Content-type: application/json'; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$context = [ |
43
|
|
|
'http' => [ |
44
|
|
|
'method' => $endpoint->getMethod(), |
45
|
|
|
'header' => implode("\r\n", $headers), |
46
|
|
|
'user_agent' => 'africc-pdns-client/1.0 (+https://github.com/AfriCC/php-pdns-client)', |
47
|
|
|
'protocol_version' => 1.1, |
48
|
|
|
'timeout' => 30, |
49
|
|
|
'ignore_errors' => true, |
50
|
|
|
] |
51
|
|
|
]; |
52
|
|
|
|
53
|
|
|
if ($endpoint->hasPayload()) { |
54
|
|
|
$context['http']['content'] = $endpoint->getPayload(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$context = stream_context_create($context); |
58
|
|
|
|
59
|
|
|
$result = @file_get_contents($this->url($endpoint->getUri()), false, $context); |
60
|
|
|
if ($result === false) { |
61
|
|
|
throw new Exception('Unable to connect to PDNS API'); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$result = json_decode($result); |
65
|
|
|
if (!empty($result->error)) { |
66
|
|
|
throw new Exception($result->error, $this->getHttpResponseCode($http_response_header)); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $result; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected function url($uri) |
73
|
|
|
{ |
74
|
|
|
return $this->api_url . $uri; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
protected function getHttpResponseCode(array $http_response_header) |
78
|
|
|
{ |
79
|
|
|
if (empty($http_response_header[0])) { |
80
|
|
|
return 0; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
if (!preg_match('~^HTTP/1\.[01]\s*([0-9]{3})~i', $http_response_header[0], $match)) { |
84
|
|
|
return 0; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $match[1]; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|