fix api routing and config paths
This commit is contained in:
+11
-4
@@ -16,9 +16,17 @@ class Router {
|
||||
public function get($path, $handler) { $this->register('GET', $path, $handler); }
|
||||
public function post($path, $handler) { $this->register('POST', $path, $handler); }
|
||||
|
||||
private function normalizePath(string $path): string {
|
||||
$path = '/' . trim($path, '/');
|
||||
$path = preg_replace('#^/api(?=/|$)#i', '', $path);
|
||||
$path = '/' . trim($path, '/');
|
||||
|
||||
return $path === '' ? '/' : $path;
|
||||
}
|
||||
|
||||
public function dispatch(Request $req, Response $res) {
|
||||
$method = $req->method();
|
||||
$path = $req->path();
|
||||
$path = $this->normalizePath($req->path());
|
||||
|
||||
// extract version prefix /v1/...
|
||||
if (preg_match('#^/v([0-9]+)(/.*)?$#', $path, $m)) {
|
||||
@@ -39,9 +47,9 @@ class Router {
|
||||
// handler can be 'UsersController@index' or 'Controllers\\UsersController@index'
|
||||
if (strpos($handler, '@') !== false) {
|
||||
list($class, $function) = explode('@', $handler);
|
||||
// if class not namespaced, prefix with Controllers\V{n}\
|
||||
// if class not namespaced, prefix with Api\\Controllers\\V{n}\\
|
||||
if (strpos($class, '\\') === false) {
|
||||
$class = "Controllers\\V{$version}\\" . $class;
|
||||
$class = "Api\\Controllers\\V{$version}\\" . $class;
|
||||
}
|
||||
} else {
|
||||
return $res->json(['error' => 'Invalid handler'], 500);
|
||||
@@ -51,7 +59,6 @@ class Router {
|
||||
return $res->json(['error' => 'Controller not found'], 500);
|
||||
}
|
||||
|
||||
// snippet inside Router::dispatch
|
||||
$controller = $this->container->make($class);
|
||||
return $controller->$function($req, $res);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user