1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* Copyright (C) 2024 Rafael San José <[email protected]> |
4
|
|
|
* |
5
|
|
|
* This program is free software; you can redistribute it and/or modify |
6
|
|
|
* it under the terms of the GNU General Public License as published by |
7
|
|
|
* the Free Software Foundation; either version 3 of the License, or |
8
|
|
|
* any later version. |
9
|
|
|
* |
10
|
|
|
* This program is distributed in the hope that it will be useful, |
11
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
12
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13
|
|
|
* GNU General Public License for more details. |
14
|
|
|
* |
15
|
|
|
* You should have received a copy of the GNU General Public License |
16
|
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
namespace Alxarafe\Tools\Dispatcher; |
20
|
|
|
|
21
|
|
|
use Alxarafe\Base\Controller\ApiController; |
22
|
|
|
use Alxarafe\Lib\Routes; |
23
|
|
|
use Alxarafe\Tools\Debug; |
24
|
|
|
|
25
|
|
|
class ApiDispatcher extends Dispatcher |
26
|
|
|
{ |
27
|
|
|
protected static function dieWithMessage($message) |
28
|
|
|
{ |
29
|
|
|
Debug::message('ApiDispatcher error:'); |
30
|
|
|
ApiController::badApiCall(); |
31
|
|
|
die(); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Run the API call for the indicated module, if it exists. |
36
|
|
|
* Execution die with a json response. |
37
|
|
|
* |
38
|
|
|
* @param $route |
39
|
|
|
* @return void |
40
|
|
|
*/ |
41
|
|
|
public static function run($route) |
42
|
|
|
{ |
43
|
|
|
$array = explode('/', $route); |
44
|
|
|
$module = $array[0]; |
45
|
|
|
$controller = $array[1] ?? null; |
46
|
|
|
$method = $array[2] ?? null; |
|
|
|
|
47
|
|
|
|
48
|
|
|
$routes = Routes::getAllRoutes(); |
49
|
|
|
$endpoint = $routes['Api'][$module][$controller] ?? null; |
50
|
|
|
if ($endpoint === null) { |
51
|
|
|
Debug::message("Dispatcher::runApi error: $route does not exists"); |
52
|
|
|
ApiController::badApiCall(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
Debug::message("Dispatcher::runApi executing $route ($endpoint)"); |
56
|
|
|
$route_array = explode('|', $endpoint); |
57
|
|
|
$className = $route_array[0]; |
58
|
|
|
$filename = $route_array[1]; |
59
|
|
|
|
60
|
|
|
if (!file_exists($filename)) { |
61
|
|
|
Debug::message("Dispatcher::runApi error: $filename does not exists"); |
62
|
|
|
ApiController::badApiCall(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
require_once $filename; |
66
|
|
|
|
67
|
|
|
$controller = new $className(); |
68
|
|
|
if ($controller === null) { |
69
|
|
|
Debug::message("Dispatcher::runApi error: $className not found"); |
70
|
|
|
ApiController::badApiCall(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.