-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.php
123 lines (110 loc) · 2.95 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
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
<?php
// cURL API wrapper class
class API_Thingy
{
// credentials we need
protected $credentials;
/**
* @param array $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;
}
/**
* @param string $endpoint
* @return mixed|null
*/
function get($endpoint = '')
{
return $this->api($endpoint, "GET");
}
/**
* @param string $endpoint
* @param array $payload
* @return mixed|null
*/
function post($endpoint = '', $payload = array())
{
return $this->api($endpoint, "POST", $payload);
}
/**
* @param string $endpoint
* @param array $payload
* @return mixed|null
*/
function patch($endpoint = '', $payload = array())
{
return $this->api($endpoint, "PATCH", $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);
switch($method)
{
case "POST":
curl_setopt($process, CURLOPT_POST, 1);
break;
case "PATCH":
curl_setopt($process, CURLOPT_CUSTOMREQUEST, $method);
break;
case "PUT":
curl_setopt($process, CURLOPT_CUSTOMREQUEST, $method);
break;
}
if (! empty($payload))
{
$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);
}
}