-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.php
333 lines (277 loc) · 9.24 KB
/
router.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
require_once ('./query-engine.php');
$r = new Gateway(FALSE);
$r->handle();
// ==================================================================
//
// This class waits for a client's instruction via GET / POST and
// invokes the appropriate class and method as determined by the client
// You can think of this as a RESFUL server implementation, with the
// exception that this server doesn't has mod_rewrite. Which means
// we can only obtain params from client via POST or GET query string
//
//
// *Note: All POST request from client must be in JSON format
// {"class":"className", "method":"methodName", "param":"arg1,arg2,arg3"}
// {"class":"className", "method":"methodName", "param": {"type":"my_type", "serial": "123", "country":"myCountry"} }
//
// *All GET URL request from client should follow this format:
// gateway.php?class=className&method=methodName¶m=arg1,arg2,arg3
// gateway.php?class=className&method=methodName¶m=type=my_type,serial=123,country=myCountry
//
// The params are supplied in this manner -> Class::Method(params_data_goes_here)
// ------------------------------------------------------------------
class Gateway
{
// ##################################################################
// Constants
// ------------------------------------------------------------------
/**
* These 3 variables are used as keys to extract data from _GET
* or from POST JSON data.
*/
const CLASS_KEY = 'class';
const METHOD_KEY = 'method';
const PARAM_KEY = 'param';
// ##################################################################
// Public variables
// ------------------------------------------------------------------
/**
* URL of the currently mapped service
* @var string
*/
public $url;
/**
* Http request method of the current request.
* Any value between [GET, PUT, POST, DELETE]
* @var string
*/
public $request_method;
/**
* Stores the location of this file.
* @var string
*/
public $root_dir;
/**
* Data sent to the service
* @var array
*/
public $request_data = array();
// ##################################################################
// Protected variables
// ------------------------------------------------------------------
/**
* When set to FALSE, it will run in debug mode
* @var boolean
*/
protected $production_mode;
/**
* Referenced to process handler via reflections
* @var boolean
*/
protected $engine;
// ##################################################################
// Private variables
// ------------------------------------------------------------------
// ==================================================================
//
// Public functions
//
// ------------------------------------------------------------------
/**
* Constructor
* @param boolean $production_mode When set to FALSE
*/
public function __construct($production_mode = FALSE)
{
$this->production_mode = $production_mode;
$this->root_dir = getcwd();
}
/**
* This implements the destructor.
*/
public function __destruct()
{
// left empty for now
}
/**
* Starts and listens to incoming request from client.
* Returns appropriate response based on client's instructions
* You can think of this as the Main() function.
*/
public function handle()
{
$this->request_method = $this->getRequestMethod();
$this->my_echo( "\n request_method is: " . $this->request_method );
$this->request_data = $this->getRequestData();
$client_request = $this->mapClassInvocation($this->request_data);
$this->handleClassInvocation($client_request);
}
/**
* @param string $class name of the engine processor code
* @param string $method specify a method to be invoked on the class
* @param $params_array to be passed on to method
* @throws todo: Throws Exception when supplied with invalid class name
*/
public function invokeClass($class_name, $method, $params_array)
{
$object = new $class_name(); //class_name case-insensitive
$reflection = new ReflectionClass($object);
if(!method_exists($class_name, $method)) {
return "Error, class: " . $class_name . "::" . $method . " doesnt exist";
}
// Get desired method
$method = $reflection->getMethod($method);
$params_array = array_filter($params_array);
if(!empty( $params_array )) { //invoke method with params
return $method->invoke($object, $params_array );
}
return $method->invoke($object);
}
/**
* Compare two strings and remove the common
* sub string from the first string and return it
* @param string $first
* @param string $second
* @param string $char optional, set it as
* blank string for char by char comparison
* @return string
*/
public function removeCommonPath($first, $second, $char = '/')
{
$first = explode($char, $first);
$second = explode($char, $second);
while (count($second)) {
if ($first[0] == $second[0]) {
array_shift($first);
} else {
break;
}
array_shift($second);
}
return implode($char, $first);
}
// ==================================================================
//
// Protected functions
//
// ------------------------------------------------------------------
/**
* Parses the request to figure out the http request type
* @return string which will be one of the following
* [GET, POST, PUT, DELETE]
* @example GET
*/
protected function getRequestMethod()
{
$method = $_SERVER['REQUEST_METHOD'];
if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { // for older clients w/o PUT, UPDATE mthodds etc.
$method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
}
//support for HEAD request
if ($method == 'HEAD') {
$method = 'GET';
}
return $method;
}
/**
* Parses the request data and returns it
* @return array php data
*/
protected function getRequestData()
{
$r = file_get_contents('php://input');
if (empty($r) || is_null($r)) {
return $_GET;
}
return is_null($r) ? array() : $r;
}
/**
* Determine which class should be invoked in accordance with
* the request instructions from client.
* All client request would be a POST JSON type, or GET type
* Other type of request parse could be further added. But JSON is sufficient for now.
* @param payload $request_data from client
* @return PHP array consisting of class, method and arguments to invoke
*/
protected function mapClassInvocation($request_data)
{
$invoke_list = array(
Gateway::CLASS_KEY => 'NoClassSpecified',
Gateway::METHOD_KEY => 'NoMethodSpecified',
Gateway::PARAM_KEY => array(),
);
// if GET request, data returned would be in PHP array obj
if($this->request_method == 'GET') {
$invoke_list[Gateway::CLASS_KEY] = $_GET[Gateway::CLASS_KEY];
$invoke_list[Gateway::METHOD_KEY] = $_GET[Gateway::METHOD_KEY];
//Start Parsing Params. GET params are specified in a comma seperated fashion
$comma_seperated_params = explode(',' , $_GET[Gateway::PARAM_KEY]);
$parsed_params = $this->parseParam ($comma_seperated_params);
$invoke_list[Gateway::PARAM_KEY] = $parsed_params;
return $invoke_list;
}
// if POST request, data returned in JSON string format
if($this->request_method == 'POST') {
$post_data = json_decode( $this->request_data , true); //json_decode handles all the parsing :)
$invoke_list[Gateway::CLASS_KEY] = $post_data[Gateway::CLASS_KEY];
$invoke_list[Gateway::METHOD_KEY] = $post_data[Gateway::METHOD_KEY];
$invoke_list[Gateway::PARAM_KEY] = $post_data[Gateway::PARAM_KEY];
// If param is not set, set it to be default value of empty array();
if(!isset($invoke_list[Gateway::PARAM_KEY])) {
$invoke_list[Gateway::PARAM_KEY] = array();
}
return $invoke_list;
}
return $invoke_list;
}
/**
* Takes in a request array and invoke the necessary class
* @param payload $request_array from client
* @return Data after invocation of the required class::method
*/
protected function handleClassInvocation($request_array)
{
$this->invokeClass(
$request_array[Gateway::CLASS_KEY],
$request_array[Gateway::METHOD_KEY],
$request_array[Gateway::PARAM_KEY]
);
}
/**
* This method extracts the param data sent by a client, and
* converts it into a hashmap.
*
* Example conversion:
* array ([0] => days=1, [1] => type=fruit ) into
* array ([days] => 1, [type] => fruit)
*
* @param $param_array are param data set coming from the client.
*/
protected function parseParam($param_array)
{
$parsedArray = array();
foreach ($param_array as $key => $value) { // extract the value
list($newKey, $newValue) = explode('=', $value);
$parsedArray[$newKey] = $newValue;
}
return $parsedArray;
}
// ==================================================================
//
// private functions
//
// ------------------------------------------------------------------
private function my_echo ($string)
{
if(!$this->production_mode) echo "DEBUG: " . $string . " \n" ;
}
private function my_print_r($data)
{
if(!$this->production_mode) {
echo "DEBUG: \n";
print_r($data);
}
}
}
?>