/
api.php
88 lines (67 loc) · 2.15 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
{
function __construct($schema)
{
preg_match('/\Ahttp:\/\/[^\/]+/', $schema, $endpoint);
$this->endpoint = $endpoint[0];
}
function batch($params)
{
$result = $this->request('POST', '/batch', [], $params);
$array = [];
foreach($result as $name => $value)
{
$array[$name] = json::decode(json::encode($value)); # TODO: Replace with fast solution
}
return $array;
}
function request($type, $url, $get = [], $post = [])
{
$developer = cookie::developer();
if($developer)
{
$get['_mode'] = 'developer';
}
$request = ['method' => $type, 'protocol_version' => '1.1', 'header' => 'Connection: Close'];
foreach($post as $name => &$param)
{
if(is_array($param) and empty($param))
{
$param = '_empty_array';
}
}
if(!empty($post))
{
$request['header'] .= "\r\nContent-type: application/x-www-form-urlencoded";
$request['content'] = http_build_query($post);
}
$ctx = stream_context_create(['http' => $request]);
$response = file_get_contents($this->endpoint . (empty($get) ? $url : ($url . '?' . http_build_query($get))), false, $ctx);
$object = json::decode($response, true);
if(is_null($object))
{
if($developer)
{
var_dump($response);
die();
}
else
{
throw new Exception("Error Processing Request", 1);
}
}
$content = $object['content'];
return (is_object($content) or (is_array($content) and array_values($content) !== $content)) ? (object) $content : $content;
}
function get($url, $params = [])
{
return $this->request('GET', $url, $params);
}
function post($url, $post = [], $get = [])
{
return $this->request('POST', $url, $get, $post);
}
private $endpoint;
}
?>