fix api routing and config paths

This commit is contained in:
2026-07-16 12:17:47 +02:00
parent ccd91b4f0f
commit fa663a6a6c
5 changed files with 22 additions and 11 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
<?php
namespace Api\Controllers\v1;
namespace Api\Controllers\V1;
use Api\Core\Request;
use Api\Core\Response;
+2 -2
View File
@@ -7,14 +7,14 @@ class Config {
private function loadConfig() {
if ($this->config === null) {
$file = __DIR__ . '/../../config/config.php';
$file = __DIR__ . '/../../../config/config.php';
$this->config = file_exists($file) ? require $file : [];
}
}
private function loadSecrets() {
if ($this->secrets === null) {
$file = __DIR__ . '/../../config/secrets.php';
$file = __DIR__ . '/../../../config/secrets.php';
$this->secrets = file_exists($file) ? require $file : [];
}
}
+11 -4
View File
@@ -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);
}