forked from maxkirchoff/UPGRAYDD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
88 lines (76 loc) · 2.11 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
<?php
class API_Thingy
{
protected $credentials;
function __construct($credentials = array())
{
if (! empty($credentials))
{
$this->credentials = $credentials;
}
}
/**
* Grab our config
*
* @return mixed
*/
function get_config()
{
// CONF
if (! file_exists('conf/conf.php'))
{
die("You need a conf.php, bro.");
}
// REQUIRE!
$config = include 'conf/conf.php';
// RETURN!
return $config;
}
function get($endpoint = '')
{
return $this->api($endpoint, "GET");
}
function post($endpoint = '', $payload = array())
{
return $this->api($endpoint, "POST", $payload);
}
/**
* Make an api request
*
* @param string $endpoint
* @param string $method
* @param array $payload
* @return mixed|null
*/
function api($endpoint = '', $method = 'GET', $payload = array())
{
// Grab our config
$config = $this->get_config();
// construct our api full url
$api_url = "http://{$config['host']}/api/v1/{$endpoint}";
try
{
$process = curl_init($api_url);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (! empty($this->credentials))
{
curl_setopt($process, CURLOPT_USERPWD, $this->credentials['username'] . ":" . $this->credentials['password']);
}
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
if ($method == "POST" && (! empty($payload)))
{
curl_setopt($process, CURLOPT_POST, 1);
$encoded_payload = json_encode($payload);
curl_setopt($process, CURLOPT_POSTFIELDS, $encoded_payload);
}
$response = curl_exec($process);
curl_close($process);
}
catch (Exception $e)
{
return null;
}
return json_decode($response, true);
}
}