-
Notifications
You must be signed in to change notification settings - Fork 2
/
Request.php
87 lines (78 loc) · 2.08 KB
/
Request.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
<?php
class Request {
public $path = array();
public $method = '';
public $query = '';
public $args = array();
function __construct() {
$request = explode('/', $_SERVER['REQUEST_URI']);
$scriptName = explode('/', $_SERVER['SCRIPT_NAME']);
$this->path = array_map('strtolower', array_values(array_diff($request, $scriptName)));
$this->method = strtolower($_SERVER['REQUEST_METHOD']);
$this->query = parse_url(strtolower($_SERVER['REQUEST_URI']));
$this->query = !empty($this->query['query']) ? $this->query['query'] : '';
$this->args = $this->get_args();
}
/**
* Get the arguments for the request.
* @return array
*/
private function get_args() {
$args = array();
switch ($this->method) {
case 'get':
if ($this->query) {
parse_str($this->query, $args);
}
break;
case 'post':
$args = $_POST;
break;
case 'put':
parse_str(file_get_contents('php://input'), $args);
break;
case 'delete':
parse_str(file_get_contents('php://input'), $args);
break;
}
return $args;
}
/**
* Handle the request made.
*/
public function handleRequest() {
$resource = null;
// Always return 200 for options requests...
if ($this->method == 'options') {
return new Response(200);
}
// Make sure they provide a type...
if (!empty($this->path[0])) {
// Get the params.
$params = $this->args;
// If the ID is provided from the path.
if (!empty($this->path[1])) {
$params['id'] = $this->path[1];
}
switch ($this->path[0]) {
case 'img':
$resource = new Image($params);
break;
case 'inst':
$resource = new Instance($params);
break;
case 'der':
$resource = new Derivative($params);
break;
}
}
// Return the resource or 406 if no resource exists...
if ($resource) {
return $resource->handleRequest($this);
}
else {
return new Response(406, 'Unknown resource.');
}
}
}
?>