-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestServer.php
executable file
·114 lines (89 loc) · 3.26 KB
/
RestServer.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
<?php
# https://github.com/jakesankey/PHP-RestServer-Class/blob/master/RestServer.php
class RestServer {
private $serviceClasses = array();
public function addServiceClass($serviceClass) {
$this->serviceClasses[count($this->serviceClasses)] = $serviceClass;
}
public function handle() {
$requestAttributes = $this->getRequestAttributeArray();
/*
*
* headers added no cache
*
* moved here to cover all outcomes sucesss/fail
*
*/
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
if ($this->methodIsDefinedInRequest())
{
$method = $requestAttributes["method"];
$serviceClass = $this->getClassContainingMethod($method);
if ($serviceClass != null)
{
$ref = new ReflectionMethod($serviceClass, $method);
if (!$ref->isPublic())
{
echo json_encode(array('error' => 'API call is invalid.'));
return ;
}
$params = $ref->getParameters();
$paramCount = count($params);
$pArray = array();
$paramStr = "";
$iterator = 0;
foreach ($params as $param)
{
$pArray[strtolower($param->getName())] = null;
$paramStr .= $param->getName();
if ($iterator != $paramCount-1) {
$paramStr .= ", ";
}
$iterator++;
}
foreach ($pArray as $key => $val) {
$pArray[strtolower($key)] = $requestAttributes[strtolower($key)];
}
if (count($pArray) == $paramCount && !in_array(null, $pArray)) {
$result = call_user_func_array(array($serviceClass, $method), $pArray);
if ($result != null)
{
echo json_encode($result);
}
}
else
{
echo json_encode(array('error' => "Required parameter(s) for ". $method .": ". $paramStr));
}
}
else
{
echo json_encode(array('error' => "The method " . $method . " does not exist."));
}
}
else
{
echo json_encode(array('error' => 'No method was requested.'));
}
}
private function getClassContainingMethod($method) {
$serviceClass = null;
foreach ($this->serviceClasses as $class) {
if ($this->methodExistsInClass($method, $class)) {
$serviceClass = $class;
}
}
return $serviceClass;
}
private function methodExistsInClass($method, $class) {
return method_exists($class, $method);
}
private function methodIsDefinedInRequest() {
return array_key_exists("method", $this->getRequestAttributeArray());
}
private function getRequestAttributeArray() {
return array_change_key_case($_REQUEST, CASE_LOWER);;
}
}