-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestServiceFactory.php
More file actions
245 lines (227 loc) · 8.55 KB
/
RestServiceFactory.php
File metadata and controls
245 lines (227 loc) · 8.55 KB
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
<?php
/**
* Definition of RestServiceFactory
*
* @copyright 2014-today Justso GmbH
* @author j.schirrmacher@justso.de
* @package jsutso\service
*/
namespace justso\justapi;
/**
* Creates REST services
*
* @package justso\service
*/
class RestServiceFactory
{
/**
* List of services in this project
* @var string[]
*/
private $services;
/**
* @var SystemEnvironmentInterface
*/
private $environment;
/**
* Initializes the factory
* @param SystemEnvironmentInterface $environment
* @param null $services
*/
public function __construct(SystemEnvironmentInterface $environment, $services = null)
{
if ($services === null) {
$config = $environment->getBootstrap()->getConfiguration();
$services = isset($config['services']) ? $config['services'] : array();
}
$this->services = $services;
$this->environment = $environment;
date_default_timezone_set('UTC');
}
/**
* Handles a request by instantiating the matching REST service class in the current project.
*/
public function handleRequest()
{
try {
$server = $this->environment->getRequestHelper()->getServerParams();
$serviceName = preg_replace('/^(.*?)(\?.*)?$/', '$1', $this->getURI($server));
$className = $this->findServiceClassName($this->services, $serviceName);
$method = $this->getMethod($server);
$this->handleAllowedOrigins();
if ($method != 'options') {
$this->callService($className, $serviceName, $method);
}
} catch (InvalidParameterException $e) {
$msg = $e->getMessage() ?: "Missing parameter";
$this->environment->sendResult('400 Bad Request', 'text/plain; charset=utf-8', $msg);
} catch (DenyException $e) {
$this->environment->sendResult('403 Forbidden', "text/plain; charset=utf-8", $e->getMessage());
} catch (\Exception $e) {
$this->environment->sendResult('500 Server error', "text/plain; charset=utf-8", $e->getMessage());
}
}
/**
* Extracts request parameters to the given environment
*
* @param SystemEnvironmentInterface $environment
*/
private function extractParameters(SystemEnvironmentInterface $environment)
{
$server = $this->environment->getRequestHelper()->getServerParams();
$params = array();
parse_str(isset($server['QUERY_STRING']) ? $server['QUERY_STRING'] : '', $params);
$body = $this->environment->getStdInput();
$content_type = isset($server['CONTENT_TYPE']) ? $server['CONTENT_TYPE'] : '';
if (strchr($content_type, ';') !== false) {
list($content_type) = preg_split('/;/', $content_type, 2);
}
switch ($content_type) {
case "application/json":
$params = array_merge($params, $this->parseApplicationJson($body));
break;
case "application/x-www-form-urlencoded":
$params = array_merge($params, $this->parseApplicationFormUrlEncoded($body));
break;
case "multipart/form-data":
$params = array_merge($params, $this->parseMultipartFormdata($body));
break;
}
$environment->getRequestHelper()->fillWithData($params);
}
/**
* Searches the services list for a matching service specification and returns the corresponding class name.
*
* @param mixed[] $services list of services
* @param string $serviceName name of requested service
*
* @throws \Exception if no matching service was found
* @return string class name
*/
private function findServiceClassName($services, $serviceName)
{
$candidates = array_filter(array_keys($services), function ($service) use ($serviceName) {
$service = str_replace(array('/', '*', '-'), array('\\/', '.*', '\\-'), $service);
return preg_match('/^' . $service . '$/', $serviceName);
});
if (count($candidates) > 0) {
$prefix = preg_replace('/\*$/', '', current($candidates));
$info = $services[current($candidates)];
if (strpos($info, 'file:') === 0) {
$appFile = $this->environment->getBootstrap()->getAppRoot() . '/' . str_replace('file:', '', $info);
$config = json_decode(file_get_contents($appFile), true);
return $this->findServiceClassName($config['services'], str_replace($prefix, '', $serviceName));
} else {
return $info;
}
}
throw new \Exception("Unknown service: '{$serviceName}'");
}
private function handleAllowedOrigins()
{
$env = $this->environment;
$allowedOrigins = $env->getBootstrap()->getAllowedOrigins();
if ($allowedOrigins !== '') {
$env->sendHeader('Access-Control-Allow-Origin: ' . $allowedOrigins);
$env->sendHeader('Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS');
$env->sendHeader('Access-Control-Allow-Headers: Token, Content-Type, Origin, Accept, x-requested-with');
}
}
/**
* @param $className
* @param $serviceName
* @param $method
* @throws InvalidParameterException
*/
private function callService($className, $serviceName, $method)
{
/** @var $service RestService */
$service = $this->environment->getDIC()->get($className, [$this->environment, $serviceName]);
$service->setName($serviceName);
$this->extractParameters($this->environment);
$verb = $method . 'Action';
if (!method_exists($service, $verb)) {
throw new InvalidParameterException("The request method is not defined in this service");
}
$service->$verb();
}
/**
* @param string[] $server
* @return string
* @throws InvalidParameterException
*/
private function getMethod($server)
{
if (empty($server['REQUEST_METHOD'])) {
throw new InvalidParameterException("Missing request method");
}
return strtolower($server['REQUEST_METHOD']);
}
/**
* @param string[] $server
* @return string
* @throws InvalidParameterException
*/
private function getURI($server)
{
if (empty($server['REQUEST_URI'])) {
throw new InvalidParameterException("Missing information about service URI");
}
return $server['REQUEST_URI'];
}
private function parseApplicationFormUrlEncoded($body)
{
$postvars = [];
parse_str($body, $postvars);
return $postvars;
}
private function parseApplicationJson($body)
{
return json_decode($body, true);
}
private function parseMultipartFormdata($body)
{
$params = [];
$boundary = substr($body, 0, strpos($body, "\r\n"));
foreach (array_slice(explode($boundary, $body), 1) as $part) {
if ($part === "--\r\n") {
break;
}
$part = ltrim($part, "\r\n");
list($rawHeaders, $content) = explode("\r\n\r\n", $part, 2);
$content = substr($content, 0, strlen($content) - 2);
$headers = [];
foreach (explode("\r\n", $rawHeaders) as $header) {
list($name, $value) = explode(':', $header);
$headers[strtolower($name)] = ltrim($value, ' ');
}
if (isset($headers['content-disposition'])) {
preg_match(
'/^(.+); *name="(([\w_]+)(\[([\w_]*)\])?)"(; *filename="([^"]+)")?/',
$headers['content-disposition'],
$matches
);
$param = $matches[3];
if (isset($matches[7])) {
$params[$param] = [
'name' => $matches[7],
'content' => $content,
'type' => $headers['content-type']
];
} elseif (isset($matches[4])) {
if ($matches[4] === '[]') {
if (!isset($params[$param])) {
$params[$param] = [];
}
$params[$param][] = $content;
} else {
$params[$param][$matches[5]] = $content;
}
} else {
$params[$param] = $content;
}
}
}
return $params;
}
}