This repository was archived by the owner on May 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAPIJet.php
More file actions
241 lines (199 loc) · 7.13 KB
/
APIJet.php
File metadata and controls
241 lines (199 loc) · 7.13 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
<?php
namespace APIJet;
class APIJet
{
const fileExt = '.php';
private $singletonContainer;
private $container;
private $authorizationCallback = null;
private $defaultResponseLimit = 25;
private $authorizationExceptionResources = '';
public function __construct(array $userConfig = [], array $containers = [])
{
if (!isset($containers['Config'])) {
$containers['Config'] = new Config();
}
$config = $containers['Config'];
$config->set($userConfig);
$this->singletonContainer = $containers;
}
public static function registerAutoload()
{
spl_autoload_register(__NAMESPACE__ . "\\APIJet::autoload");
}
/**
* @desc PSR-0
* @link http://www.php-fig.org/psr/psr-0/
*/
public static function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . self::fileExt;
// Original PSR-0
// require $fileName;
// Adapted
require '../'.$fileName;
}
public function getSingletonContainer($name)
{
if (isset($this->singletonContainer[$name])) {
$instance = $this->singletonContainer[$name];
if ($instance instanceof \Closure) {
$this->singletonContainer[$name] = $instance();
}
return $this->singletonContainer[$name];
}
trigger_error('Singleton container with '.$name.' does not exist', E_USER_ERROR);
}
public function setSingletonContainer($name, $instance)
{
$this->singletonContainer[$name] = $instance;
}
public function getContainer($name)
{
if (isset($this->container[$name])) {
$instance = $this->container[$name];
if ($instance instanceof \Closure) {
return $instance();
}
trigger_error('Container with '.$name.' name should be Closure', E_USER_ERROR);
}
trigger_error('Container with '.$name.' does not exist', E_USER_ERROR);
}
public function setContainer($name, $instance)
{
$this->container[$name] = $instance;
}
/**
* @return Router
*/
public function getRouterContainer()
{
return $this->getSingletonContainer('Router');
}
/**
* @return Config
*/
public function getConfigContainer()
{
return $this->getSingletonContainer('Config');
}
/**
* @return Request
*/
public function getRequestContainer()
{
return $this->getSingletonContainer('Request');
}
/**
* @return Response
*/
public function getResponseContainer()
{
return $this->getSingletonContainer('Response');
}
/**
* @desc Initialize basic container excluding config
*/
private function initBaseContainers($containers)
{
$config = $this->getConfigContainer();
$routerConfig = $config->get('Router');
if (!isset($containers['Router'])) {
$containers['Router'] = new Router();
}
$routerContainer = $containers['Router'];
$routerContainer->setRoutes($routerConfig['routes']);
$routerContainer->setGlobalPattern($routerConfig['globalPattern']);
if (!isset($containers['Request'])) {
$containers['Request'] = new Request();
}
$requestContainer = $containers['Request'];
$requestContainer->setAuthorizationCallback($this->authorizationCallback);
$requestContainer->setDefaultResponseLimit($this->defaultResponseLimit);
if (!isset($containers['Response'])) {
$containers['Response'] = new Response();
}
$this->singletonContainer = $containers + $this->singletonContainer;
}
public function setAuthorizationCallback($authorizationCallback, $exceptionResources = '')
{
$this->authorizationCallback = $authorizationCallback;
$this->authorizationExceptionResources = $exceptionResources;
}
public function setDefaultResponseLimit($defaultResponseLimit)
{
$this->defaultResponseLimit = $defaultResponseLimit;
}
public function run($containers = [])
{
$this->initBaseContainers($containers);
$request = $this->getRequestContainer();
$response = $this->getResponseContainer();
$requestUrl = $request::getCleanRequestUrl();
// don't check authorization if the current resource url is in exception.
if (! (bool) preg_match('#^'.$this->authorizationExceptionResources.'$#', $requestUrl)) {
if (!$request->isАuthorized()) {
$response->setCode(401);
$response->render();
return;
}
}
$router = $this->getRouterContainer();
if (!$router->getMatchedRouterResource($request::getMethod(), $requestUrl)) {
$response->setCode(404);
} else {
try {
$actionResponse = $this->executeResoruceAction(
$router->getMatchedController(),
$router->getMatchedAction(),
$router->getMatchedRouteParameters()
);
if ($actionResponse === false) {
$response->setCode(404);
} else {
$response->setBody($actionResponse);
}
} catch(\APIJet\CustomException $e) {
$response->setCode($e->getHttpCode());
$response->setBody($e->getErrorBody());
} catch(\Exception $e) {
$response->setCode(500);
}
}
$response->render();
}
/**
* @return response of executed action or false in case it doesn't exist
* @param string $controller
* @param string $action
* @param string $parameters
*/
private function executeResoruceAction($controller, $action, $parameters)
{
$controller = ucfirst($controller);
$action = strtolower($this->getRequestContainer()->getMethod()).'_'.$action;
$controller = 'Controllers\\'.$controller;
// Check if class exist
if (!class_exists($controller)) {
return false;
}
$controllerInstance = new $controller($this);
// Check if action exist
if (!method_exists($controllerInstance, $action)) {
return false;
}
// Check if it's a callable method
if (!is_callable([$controllerInstance, $action])) {
return false;
}
return (array) call_user_func_array(array($controllerInstance, $action), $parameters);
}
}