-
Notifications
You must be signed in to change notification settings - Fork 3
/
rest_router.module
377 lines (339 loc) · 9.51 KB
/
rest_router.module
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
/**
* @file
* REST router API module which provides a way to create multiple drupal REST
* endpoints with URL definition similar to core hook_menu().
*/
/**
* Implements hook_menu().
*/
function rest_router_menu() {
$items = array();
// Get list of all endpoints
$endpoints = rest_router_get_endpoints();
// For each endpoint create general menu handler which
// will process requests on defined URL
foreach ($endpoints as $name => $endpoint) {
$items[$endpoint['path']] = array(
'page callback' => 'rest_router_handler',
'page arguments' => array($name),
'access callback' => TRUE,
);
}
return $items;
}
/**
* Get defined REST endpoints
*/
function rest_router_get_endpoints() {
$output = array();
// This is invoked on every router API request so it should be cached
// rather than collect list of available APIs by invoking hook_rest_endpoints.
if ($cache = cache_get('rest_router_endpoints')) {
$output = $cache->data;
}
else {
// Collect all module definitions
foreach (module_implements('rest_endpoints') as $module) {
$endpoints = call_user_func($module . '_rest_endpoints');
if (isset($endpoints) && is_array($endpoints)) {
foreach (array_keys($endpoints) as $path) {
$endpoints[$path]['module'] = $module;
}
$output = array_merge($output, $endpoints);
}
}
// Add default endpoint structure
foreach (array_keys($output) as $name) {
$output[$name] += array(
'auth' => array(),
'version' => array(),
'request' => array('json'),
'response' => array('json'),
);
}
cache_set('rest_router_endpoints', $output);
}
// Allow other modules to change configuration
drupal_alter('rest_endpoints', $output);
return $output;
}
/**
* Get defined REST endpoints
*
* @param $name
* Machine name of the endpoint
* @return
* Endpoint definition
*/
function rest_router_get_endpoint($name) {
$endpoints = rest_router_get_endpoints();
return isset($endpoints[$name]) ? $endpoints[$name] : NULL;
}
/**
* Determine router path without prefix
*
* @param $endpoint
* Endpoint definition
* @param $path
* Requested path
* @return
* Path without prefix
*/
function rest_router_get_path($endpoint, $path = NULL) {
$path = !empty($path) ? $path : $_GET['q'];
// If endpoint path is part of URL remove it from further processing.
if (strpos($path, $endpoint['path']) === 0) {
$path = trim(substr($path, strlen($endpoint['path'])), '/');
}
return $path;
}
/**
* Create router instance
*
* @param $request
* RestRouterRequest object
* @return
* RestRouterApiRouter object instance
*/
function rest_router_create_router(RestRouterRequest $request) {
$endpoint = $request->endpoint();
// Get router class name
$class = $endpoint['versions'][$request->getVersion()]['router'];
// Create class if is available
if ($class && class_exists($class)) {
return new $class($request);
}
else {
throw new Exception(t('Missing router class for path "@path" version "@version"', array(
'@path' => $request->getPath(),
'@version' => $request->getVersion(),
)));
}
}
/**
* Main menu handler for endpoint path
*
* @param $name
* Api endpoint callback
* @return
*/
function rest_router_handler($name) {
$response = NULL;
// Load endpoint definition. If endpoint isn't available there is
// nothing to process.
$endpoint = rest_router_get_endpoint($name);
if (empty($endpoint)) {
return MENU_NOT_FOUND;
}
// Get path cleared for endpoint base
$path = rest_router_get_path($endpoint);
// Create new request representation
$request = new RestRouterRequest($endpoint, $path);
// Allow other modules to alter request
drupal_alter('rest_router_request', $request);
try {
$request->prepare();
// Set API version
rest_router_version($request);
// Authenticate possible users
rest_router_authenticate($request);
// Create router for handling request
$router = rest_router_create_router($request);
// Process the request and get Response object
$response = $router->process();
}
// Intentionally generated exception during runtime that contains
// additional information about response
catch (RestRouterException $e) {
$response = new RestRouterErrorResponse($e->code, $e->message, $e->data);
}
// General exception that should result in HTTP 500
catch (Exception $e) {
watchdog('rest_router', '@message', array('@message' => $e->getMessage()), WATCHDOG_ERROR);
$response = new RestRouterErrorResponse(500, '');
}
// If response has been created deliver it.
if ($response) {
if (!empty($request)) {
$response->setRequest($request);
}
rest_router_deliver($response);
}
else {
return MENU_NOT_FOUND;
}
}
/**
* Deliver HTTP response
*
* @param $response
* RestRouterResponse object
*/
function rest_router_deliver(RestRouterResponse $response) {
$response->prepare();
// Set headers from response
drupal_add_http_header('Status', $response->status());
foreach ($response->headers() as $name => $value) {
drupal_add_http_header($name, $value, TRUE);
}
// If response contains body
$body = $response->body();
if (!empty($body)) {
echo $body;
}
// End drupal
drupal_exit();
}
/**
* Run authentication plugins to set correct user.
*
* @param $request
* RestRouterRequest object
*/
function rest_router_authenticate(RestRouterRequest $request) {
$plugins = rest_router_plugins('auth');
$endpoint = $request->endpoint();
// Process all plugins
foreach ($endpoint['auth'] as $name => $settings) {
if (isset($plugins[$name])) {
$plugin = new $plugins[$name]($request, $settings);
$account = $plugin->authenticate();
// User got authenticated by plugin
if (!empty($account->uid)) {
// Set new user
global $user;
drupal_save_session(FALSE);
$user = $account;
// Notify other modules that user has been authenticated
module_invoke_all('rest_router_authenticate', $name, $account);
return;
}
}
}
}
/**
* Create new redirect response for router.
*
* @param $path
* API destination path (without version)
* @param $code
* Redirect code
* @return
* RestRouterRedirectResponse
*/
function rest_router_redirect($path, $code = 301) {
return new RestRouterRedirectResponse($path, $code);
}
/**
* Retrieve version of requested API.
*
* @param $request
* RestRouterRequest object
* @return
* Version string
*/
function rest_router_version(RestRouterRequest $request) {
$plugins = rest_router_plugins('version');
$endpoint = $request->endpoint();
// Process all version parser plugins
foreach ($endpoint['version'] as $name => $settings) {
if (isset($plugins[$name])) {
$plugin = new $plugins[$name]($request, $settings);
$version = $plugin->version();
// If plugin detected API version stop processing and set
// version to API.
if ($version !== NULL) {
// If version is not available in API
if (!isset($endpoint['versions'][$version])) {
throw new RestRouterException(404, "Version not found");
}
$request->setVersion($version);
$request->setVersionHandler($plugin);
return;
}
}
}
// If endpoint definition sets default version
if (!empty($endpoint['default version'])) {
$request->setVersion($endpoint['default version']);
}
else {
throw new RestRouterException(404, 'Missing API version');
}
}
/**
* Get map of plugins of certain type.
*
* @param $type
* Type of the plugins
* 'auth', 'version'
* @return
* Array of plugins
*/
function rest_router_plugins($type = NULL) {
$plugins = array(
'auth' => array(
'oauth' => 'RestRouterAuthOAuth',
'anonymous' => 'RestRouterAuthAnonymous',
'basic' => 'RestRouterAuthBasic'
),
'version' => array(
'path' => 'RestRouterVersionPath',
'query' => 'RestRouterVersionQuery',
),
);
// Allow other modules to modify or add additional plugins.
drupal_alter('rest_plugins', $plugins);
return isset($plugins[$type]) ? $plugins[$type] : array();
}
/**
* Call API loader callback on object.
*
* @param $value
* Loader function value
* @param $object
* Api object
* @param $method
* Name of object method
* @return
* Boolean
*/
function rest_router_loader_callback($value, $object, $method) {
return call_user_func_array(array($object, $method), array($value));
}
/**
* Call API access callback on object.
*
* @param $object
* Api object
* @param $method
* Name of object method
* @return
* Boolean
*/
function rest_router_access_callback($object, $method) {
// Remove object reference and method name from args
$args = array_slice(func_get_args(), 2);
return call_user_func_array(array($object, $method), $args);
}
/**
* Call API page callback on object.
*
* @param $object
* Api object
* @param $method
* Name of object method
* @return
* Boolean
*/
function rest_router_page_callback($object, $method) {
// Remove object reference and method name from args
$args = array_slice(func_get_args(), 2);
// Call beforeRequest with method name and arguments.
call_user_func_array(array($object, 'beforeRequest'), array($method, $args));
$value = call_user_func_array(array($object, $method), $args);
// Call afterRequest with method name, arguments, and response value.
call_user_func_array(array($object, 'afterRequest'), array($method, $args, &$value));
return $value;
}