forked from APIJet/APIJet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIJet.php
More file actions
215 lines (178 loc) · 6.23 KB
/
APIJet.php
File metadata and controls
215 lines (178 loc) · 6.23 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
<?php
namespace APIJet;
class APIJet
{
const fileExt = '.php';
// List of configurable settings name.
const DEFAULT_RESPONSE_LIMIT = 0;
const AUTHORIZATION_CALLBACK = 1;
private $singletonContainer;
private static $defaultConfig =
[
'APIJet' => [
self::DEFAULT_RESPONSE_LIMIT => 25,
self::AUTHORIZATION_CALLBACK => null,
]
];
public function __construct(array $userConfig = [], array $containers = [])
{
if (!isset($containers['Config'])) {
$containers['Config'] = new Config();
}
$config = $containers['Config'];
$config->set(self::$defaultConfig);
$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;
}
/**
* @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();
$APIJetConfig = $config->get('APIJet');
$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($APIJetConfig[self::AUTHORIZATION_CALLBACK]);
$requestContainer->setDefaultResponseLimit($APIJetConfig[self::DEFAULT_RESPONSE_LIMIT]);
if (!isset($containers['Response'])) {
$containers['Response'] = new Response();
}
$this->singletonContainer = $containers + $this->singletonContainer;
}
public function run($containers = [])
{
$this->initBaseContainers($containers);
$request = $this->getRequestContainer();
$response = $this->getResponseContainer();
if (!$request->isАuthorized()) {
$response->setCode(401);
return;
}
$router = $this->getRouterContainer();
if (!$router->getMatchedRouterResource($request::getMethod(), $request::getCleanRequestUrl())) {
$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);
}
}