Skip to content

Commit eb4ef5e

Browse files
Allow RestExtension to work without database connection
1 parent 812e87e commit eb4ef5e

File tree

2 files changed

+56
-55
lines changed

2 files changed

+56
-55
lines changed

Hooks.php

+55-54
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php namespace RestExtension;
22

33
use CodeIgniter\Database\BaseConnection;
4+
use CodeIgniter\Database\Exceptions\DatabaseException;
45
use CodeIgniter\Events\Events;
56
use Config\Database;
67
use Config\OrmExtension;
@@ -64,9 +65,9 @@ public static function preSystem() {
6465
/*
6566
* Append RestExtension Entities and Models to OrmExtension namespaces
6667
*/
67-
if(!is_array(OrmExtension::$modelNamespace))
68+
if (!is_array(OrmExtension::$modelNamespace))
6869
OrmExtension::$modelNamespace = [OrmExtension::$modelNamespace];
69-
if(!is_array(OrmExtension::$entityNamespace))
70+
if (!is_array(OrmExtension::$entityNamespace))
7071
OrmExtension::$entityNamespace = [OrmExtension::$entityNamespace];
7172
OrmExtension::$modelNamespace[] = 'RestExtension\Models\\';
7273
OrmExtension::$entityNamespace[] = 'RestExtension\Entities\\';
@@ -79,7 +80,7 @@ public static function preSystem() {
7980
/*
8081
* Api Routing
8182
*/
82-
if(self::$config) {
83+
if (self::$config) {
8384

8485
/*
8586
* Setup Database connection
@@ -88,9 +89,8 @@ public static function preSystem() {
8889

8990
$routes = Services::routes(true);
9091

91-
if (self::$config->enableApiRouting && self::$database->tableExists('api_routes')) {
92-
93-
try {
92+
try {
93+
if (self::$config->enableApiRouting && self::$database->tableExists('api_routes')) {
9494
/** @var ApiRoute $apiRoutes */
9595
$apiRoutes = (new ApiRouteModel())->find();
9696

@@ -103,21 +103,22 @@ public static function preSystem() {
103103
$routes->{$route->method}($route->from, $route->to);
104104
}
105105
}
106-
} catch (\mysqli_sql_exception $e) {
107-
108106
}
107+
} catch (DatabaseException $e) {
108+
109+
} catch (\mysqli_sql_exception $e) {
109110

110111
}
111112

112113
/*
113114
* Export TypeScript Models
114115
*/
115-
if(isset(self::$config->typescriptModelExporterRoute) && self::$config->typescriptModelExporterRoute) {
116+
if (isset(self::$config->typescriptModelExporterRoute) && self::$config->typescriptModelExporterRoute) {
116117
$routes->get(self::$config->typescriptModelExporterRoute, function($debug = false) {
117118
$parser = ModelParser::run();
118119
$parser->generateTypeScript($debug);
119120

120-
if($debug) return;
121+
if ($debug) return;
121122

122123
// Zip models folder
123124
shell_exec('cd "' . WRITEPATH . 'tmp/" && zip -r models.zip models');
@@ -137,7 +138,7 @@ public static function preSystem() {
137138
/*
138139
* Export TypeScript API Class
139140
*/
140-
if(isset(self::$config->typescriptAPIExporterRoute) && self::$config->typescriptAPIExporterRoute) {
141+
if (isset(self::$config->typescriptAPIExporterRoute) && self::$config->typescriptAPIExporterRoute) {
141142
$routes->get(self::$config->typescriptAPIExporterRoute, function($debug = 0) {
142143
$parser = ApiParser::run();
143144
$parser->generateTypeScript($debug);
@@ -159,7 +160,7 @@ public static function preSystem() {
159160
/*
160161
* Export Vue API Class
161162
*/
162-
if(isset(self::$config->vueAPIExporterRoute) && self::$config->vueAPIExporterRoute) {
163+
if (isset(self::$config->vueAPIExporterRoute) && self::$config->vueAPIExporterRoute) {
163164
$routes->get(self::$config->vueAPIExporterRoute, function($debug = 0) {
164165
$parser = ApiParser::run();
165166
$parser->generateVue($debug);
@@ -181,12 +182,12 @@ public static function preSystem() {
181182
/*
182183
* Export Xamarin Models
183184
*/
184-
if(isset(self::$config->xamarinModelExporterRoute) && self::$config->xamarinModelExporterRoute) {
185+
if (isset(self::$config->xamarinModelExporterRoute) && self::$config->xamarinModelExporterRoute) {
185186
$routes->get(self::$config->xamarinModelExporterRoute, function($debug = false) {
186187
$parser = ModelParser::run();
187188
$parser->generateXamarin($debug);
188189

189-
if($debug) return;
190+
if ($debug) return;
190191

191192
// Zip models folder
192193
shell_exec('cd "' . WRITEPATH . 'tmp/xamarin/" && zip -r models.zip models');
@@ -206,7 +207,7 @@ public static function preSystem() {
206207
/*
207208
* Export Xamarin API Class
208209
*/
209-
if(isset(self::$config->xamarinAPIExporterRoute) && self::$config->xamarinAPIExporterRoute
210+
if (isset(self::$config->xamarinAPIExporterRoute) && self::$config->xamarinAPIExporterRoute
210211
&& isset(self::$config->xamarinAPINamespace) && self::$config->xamarinAPINamespace) {
211212
$routes->get(self::$config->xamarinAPIExporterRoute, function($debug = false) {
212213
$parser = ApiParser::run();
@@ -239,40 +240,40 @@ public static function preSystem() {
239240
* @throws \Exception
240241
*/
241242
public static function postControllerConstructor() {
242-
if(self::$config) {
243+
if (self::$config) {
243244

244245
$restRequest = RestRequest::getInstance();
245246
$request = Services::request();
246247

247248
/*
248249
* CLI is trusted
249250
*/
250-
if($request->isCLI()) {
251+
if ($request->isCLI()) {
251252
return;
252253
}
253254

254-
if(self::$config->enableApiRouting && self::$database->tableExists('api_routes')) {
255+
if (self::$config->enableApiRouting && self::$database->tableExists('api_routes')) {
255256

256257
/*
257258
* Search for api route based on CI's matched route
258259
*/
259260
$route = Services::router()->getMatchedRoute();
260261
if (!$route) {
261262
$url = Services::request()->uri;
262-
throw new \Exception("RestExtension: Route ($url) not found. Api Routes have to be store in the ".
263+
throw new \Exception("RestExtension: Route ($url) not found. Api Routes have to be store in the " .
263264
"database to check against scopes.");
264265
}
265266
$routeFrom = $route[0];
266267
/** @var ApiRoute $apiRoute */
267268
$apiRoute = (new ApiRouteModel())
268269
->groupStart()
269270
->where('from', $routeFrom)
270-
->orWhere('from', '/'.$routeFrom)
271+
->orWhere('from', '/' . $routeFrom)
271272
->groupEnd()
272273
->where('method', $request->getMethod())
273274
->find();
274-
if(!$apiRoute->exists() && !$request->isCLI()) {
275-
throw new \Exception("RestExtension: Route ($routeFrom) not found. Api Routes have to be store in the ".
275+
if (!$apiRoute->exists() && !$request->isCLI()) {
276+
throw new \Exception("RestExtension: Route ($routeFrom) not found. Api Routes have to be store in the " .
276277
"database to check against scopes.");
277278
}
278279
$restRequest->apiRoute = $apiRoute;
@@ -285,9 +286,9 @@ public static function postControllerConstructor() {
285286
/*
286287
* Public API route can skip authorization
287288
*/
288-
if(!$apiRoute->is_public) {
289+
if (!$apiRoute->is_public) {
289290

290-
if(!isset($authResponse->authorized) || $authResponse->authorized == false) {
291+
if (!isset($authResponse->authorized) || $authResponse->authorized == false) {
291292

292293
/*
293294
* Unauthorized!
@@ -296,7 +297,7 @@ public static function postControllerConstructor() {
296297
}
297298
}
298299

299-
if($authResponse && isset($authResponse->client_id)) {
300+
if ($authResponse && isset($authResponse->client_id)) {
300301

301302
/*
302303
* Authorized, go on
@@ -311,13 +312,13 @@ public static function postControllerConstructor() {
311312
/*
312313
* API Rate Limit
313314
*/
314-
if(self::$config->enableRateLimit && self::$database->tableExists('api_access_logs')) {
315-
if(self::$config->defaultRateLimit > 0) {
315+
if (self::$config->enableRateLimit && self::$database->tableExists('api_access_logs')) {
316+
if (self::$config->defaultRateLimit > 0) {
316317
$lastHour = (new ApiAccessLogModel())
317318
->where('client_id', $authResponse->client_id)
318319
->where('date >', date('Y-m-d H:i:s', strtotime('-1 hour')))
319320
->countAllResults();
320-
if($lastHour >= self::$config->defaultRateLimit) {
321+
if ($lastHour >= self::$config->defaultRateLimit) {
321322

322323
/*
323324
* Unauthorized!
@@ -331,14 +332,14 @@ public static function postControllerConstructor() {
331332
/*
332333
* API Usage Reporting
333334
*/
334-
if(self::$config->enableUsageReporting && self::$database->tableExists('api_usage_reports')) {
335+
if (self::$config->enableUsageReporting && self::$database->tableExists('api_usage_reports')) {
335336

336337
/** @var ApiUsageReport $usageReport */
337338
$usageReport = (new ApiUsageReportModel())
338339
->where('client_id', $authResponse->client_id)
339340
->where('date', date('Y-m-d'))
340341
->find();
341-
if(!$usageReport->exists()) {
342+
if (!$usageReport->exists()) {
342343
$usageReport->client_id = $authResponse->client_id;
343344
$usageReport->date = date('Y-m-d');
344345
$usageReport->usage = 0;
@@ -353,16 +354,16 @@ public static function postControllerConstructor() {
353354
/*
354355
* API Access Log
355356
*/
356-
if(self::$config->enableAccessLog && self::$database->tableExists('api_access_logs')) {
357+
if (self::$config->enableAccessLog && self::$database->tableExists('api_access_logs')) {
357358

358359
$apiAccessLog = new ApiAccessLog();
359-
if($restRequest->userId) {
360+
if ($restRequest->userId) {
360361
$apiAccessLog->user_id = $restRequest->userId;
361362
}
362-
if($restRequest->clientId) {
363+
if ($restRequest->clientId) {
363364
$apiAccessLog->client_id = $restRequest->clientId;
364365
}
365-
if($restRequest->apiRoute) {
366+
if ($restRequest->apiRoute) {
366367
$apiAccessLog->api_route_id = $restRequest->apiRoute->id;
367368
}
368369
$apiAccessLog->access_token = $restRequest->getAccessToken();
@@ -382,19 +383,19 @@ public static function postSystem() {
382383
/*
383384
* CLI is trusted
384385
*/
385-
if(Services::request()->isCLI())
386+
if (Services::request()->isCLI())
386387
return;
387388

388389
/*
389390
* Stop timer for benchmarking
390391
*/
391392
timer('RestExtension::timer');
392393

393-
if(self::$config) {
394+
if (self::$config) {
394395

395-
if(self::$config->enableAccessLog && self::$database->tableExists('api_access_logs')) {
396+
if (self::$config->enableAccessLog && self::$database->tableExists('api_access_logs')) {
396397
$apiAccessLog = RestRequest::getInstance()->apiAccessLog;
397-
if($apiAccessLog) {
398+
if ($apiAccessLog) {
398399
$apiAccessLog->milliseconds = timer()->getElapsedTime('RestExtension::timer') * 1000;
399400
$apiAccessLog->save();
400401
}
@@ -404,17 +405,17 @@ public static function postSystem() {
404405
}
405406

406407
public static function exceptionHandler(Throwable $exception) {
407-
if(self::$config) {
408+
if (self::$config) {
408409

409410
$request = Services::request();
410411
$restRequest = RestRequest::getInstance();
411412

412-
if(self::$config->enableErrorLog && self::$database->tableExists('api_error_logs')) {
413+
if (self::$config->enableErrorLog && self::$database->tableExists('api_error_logs')) {
413414

414415
$apiErrorLog = new ApiErrorLog();
415-
if($restRequest->userId) $apiErrorLog->user_id = $restRequest->userId;
416-
if($restRequest->clientId) $apiErrorLog->client_id = $restRequest->clientId;
417-
if($restRequest->apiRoute) $apiErrorLog->api_route_id = $restRequest->apiRoute->id;
416+
if ($restRequest->userId) $apiErrorLog->user_id = $restRequest->userId;
417+
if ($restRequest->clientId) $apiErrorLog->client_id = $restRequest->clientId;
418+
if ($restRequest->apiRoute) $apiErrorLog->api_route_id = $restRequest->apiRoute->id;
418419
$apiErrorLog->access_token = $restRequest->getAccessToken();
419420
$apiErrorLog->uri = current_url();
420421
$apiErrorLog->date = date('Y-m-d H:i:s');
@@ -429,13 +430,13 @@ public static function exceptionHandler(Throwable $exception) {
429430
$apiErrorLog->save();
430431
}
431432

432-
if($exception instanceof UnauthorizedException || $exception instanceof RateLimitExceededException) {
433+
if ($exception instanceof UnauthorizedException || $exception instanceof RateLimitExceededException) {
433434

434-
if(self::$config->enableBlockedLog && self::$database->tableExists('api_blocked_logs')) {
435+
if (self::$config->enableBlockedLog && self::$database->tableExists('api_blocked_logs')) {
435436
$apiBlockedLog = new ApiBlockedLog();
436-
if($restRequest->userId) $apiBlockedLog->user_id = $restRequest->userId;
437-
if($restRequest->clientId) $apiBlockedLog->client_id = $restRequest->clientId;
438-
if($restRequest->apiRoute) $apiBlockedLog->api_route_id = $restRequest->apiRoute->id;
437+
if ($restRequest->userId) $apiBlockedLog->user_id = $restRequest->userId;
438+
if ($restRequest->clientId) $apiBlockedLog->client_id = $restRequest->clientId;
439+
if ($restRequest->apiRoute) $apiBlockedLog->api_route_id = $restRequest->apiRoute->id;
439440
$apiBlockedLog->access_token = $restRequest->getAccessToken();
440441
$apiBlockedLog->uri = current_url();
441442
$apiBlockedLog->date = date('Y-m-d H:i:s');
@@ -446,16 +447,16 @@ public static function exceptionHandler(Throwable $exception) {
446447

447448
}
448449

449-
if($exception instanceof RestException) {
450+
if ($exception instanceof RestException) {
450451

451452
$response = Services::response();
452453
$response->setStatusCode($exception->getCode());
453454
$response->setJSON([
454-
'status' => 'ERROR',
455-
'code' => $exception->getCode(),
456-
'error' => get_class($exception),
457-
'reason' => $exception->getMessage(),
458-
'debug' => Data::getDebugger()
455+
'status' => 'ERROR',
456+
'code' => $exception->getCode(),
457+
'error' => get_class($exception),
458+
'reason' => $exception->getMessage(),
459+
'debug' => Data::getDebugger()
459460
]);
460461
$response->send();
461462
return;

ResourceControllerInterface.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@ public function _setResource($item);
1919

2020
public function error($errorCode, $statusCode = 503);
2121

22-
}
22+
}

0 commit comments

Comments
 (0)