From d903d4775934bf08e1467f1c7ac1298232fb597f Mon Sep 17 00:00:00 2001 From: Spelunky Date: Sun, 15 Feb 2026 04:19:50 +0100 Subject: [PATCH] =?UTF-8?q?Refactoring,=20README-Optimierung,=20Middleware?= =?UTF-8?q?-Beispiele=20erg=C3=A4nzt,=20Codebl=C3=B6cke=20korrigiert=20und?= =?UTF-8?q?=20Doku=20aktualisiert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 54 ++++++++ README.md | 142 +++++++++++++++----- bin/route-cache | 94 ++++++++----- example/app/Controller/HelloController.php | 13 +- example/app/Controller/RoutesController.php | 33 ++++- example/public/index.php | 19 ++- example/routes/web.php | 43 ++++-- src/Cache/RouteCache.php | 34 +++-- src/Http/Request.php | 53 +++++--- src/Http/Response.php | 13 +- src/Router.php | 111 +++++++-------- 11 files changed, 428 insertions(+), 181 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..824b0c2 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,54 @@ +# CHANGELOG + +## [Unreleased] – 2024-06 +### Refactoring & Verbesserungen + +#### Allgemein +- Umfassendes Refactoring und Aufräumen des gesamten Projekts (`src/`, `example/`, `bin/`). +- Kommentare und PHPDoc in allen Kernklassen und Beispiel-Controllern vereinheitlicht und präzisiert. +- Konsistente Typisierung und bessere Lesbarkeit im gesamten Code. +- Fehlerbehandlung und Robustheit in allen Komponenten verbessert. + +#### src/ +- **Router.php** + - Fehlerausgaben und Exception-Handling bei Controller-Handlern verbessert. + - Middleware-Stack-Fehlerausgabe verständlicher gestaltet. + - Kommentare und PHPDoc auf Deutsch und klarer formuliert. + - Kleinere Vereinheitlichungen bei Prefix- und Middleware-Behandlung. +- **Http/Response.php** + - Fehlerbehandlung bei JSON-Encoding in `withJson()` ergänzt (liefert Fehlerobjekt und Status 500 bei Encoding-Problemen). + - PHPDoc für Response-Helper vereinheitlicht. +- **Http/Request.php** + - Header-Namen werden jetzt immer als Kleinbuchstaben gespeichert und abgefragt (Case-Insensitivity). + - PHPDoc ergänzt und vereinheitlicht. + - Doppelte Dokumentation entfernt. +- **Cache/RouteCache.php** + - Fehlerbehandlung beim Schreiben, Lesen und Löschen der Cache-Datei verbessert (RuntimeException bei Problemen). + - PHPDoc ergänzt und vereinheitlicht. + +#### example/ +- **routes/web.php** + - Struktur und Kommentare vereinheitlicht (Abschnitte für GET/POST/PUT/…). + - Überflüssige Leerzeilen entfernt, Beispielrouten klar gegliedert. + - Middleware- und Gruppenbeispiele besser kommentiert. +- **public/index.php** + - Klarere Struktur und Kommentare für Bootstrap, Middleware und Error-Handler. + - Logging und Fehlerausgabe als Beispiel hervorgehoben. +- **app/Controller/HelloController.php & RoutesController.php** + - PHPDoc und Kommentare ergänzt. + - Typisierung der Methodenparameter und Rückgaben klargestellt. + - HTML-Ausgabe in `RoutesController` robuster (XSS-Schutz durch `htmlspecialchars` mit Encoding). + +#### bin/ +- **bin/route-cache** + - Kommentare und Usage-Abschnitt klarer und einheitlicher gestaltet. + - Fehlerausgaben für alle Befehle verbessert (Ausgabe auf STDERR, Exit-Code bei Fehlern). + - Code-Formatierung und Robustheit erhöht (alle Dateioperationen und dynamischen Includes in Try/Catch-Blöcke). + - Handler-String-Erkennung bei der Listen-Ausgabe robuster gemacht. + +--- + +## [Vorherige Versionen] +- Initiale Implementierung des MariaCore Routers mit PSR-Prinzipien, Middleware, Named Routes, Controller-Support, Response-Helpern, internem Forwarding, Meta-Cache und CLI-Tool. + +--- \ No newline at end of file diff --git a/README.md b/README.md index d8d816c..afe95ae 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,64 @@ Ein schlanker, moderner PHP-Router mit Middleware, Named Routes, Controller-Supp - **Optionales Routen-Caching:** Cachebare Routen als JSON speichern, CLI-Tool zur Verwaltung - **CLI-Tool:** Cache löschen, neu bauen, Routen auflisten + --- +## Middleware + +Middleware kann global, pro Route oder für ganze Gruppen verwendet werden. Sie eignet sich für Authentifizierung, Logging, CORS, etc. + +### Globale Middleware (für alle Routen) + +```php +addMiddleware(function (Request $request, callable $next) { + // Beispiel: Logging + error_log('[Router] ' . $request->getMethod() . ' ' . $request->getUri()); + // Weiter zur nächsten Middleware/Handler + return $next($request); +}); +``` + +### Middleware pro Route + +```php +get('/protected', function (Request $request, array $params) { + return (new Response())->withJson(['message' => 'Du bist authentifiziert!']); +}, [ + function (Request $request, callable $next) { + if ($request->getHeader('x-auth') !== 'geheim') { + return (new Response())->withJson(['error' => 'Nicht autorisiert'], 401); + } + return $next($request); + } +]); +``` + +### Middleware für Gruppen + +```php +group('/admin', function ($router) { + $router->get('/dashboard', function (Request $request, array $params) { + return (new Response())->withJson(['dashboard' => 'Admin stats here']); + }); +}, [ + function (Request $request, callable $next) { + if ($request->getHeader('x-admin') !== 'true') { + return (new Response())->withJson(['error' => 'Admin-Bereich!'], 403); + } + return $next($request); + } +]); +``` +--- + + ## Schnellstart ### 1. Installation @@ -58,20 +114,44 @@ $router->get('/user/{id}', function (Request $request, array $params) use ($rout 'profile_url' => $profileUrl ]); })->name('user.profile'); - -// Route mit Middleware -$router->get('/protected', function (Request $request, array $params) { - return (new Response())->withJson(['message' => 'Du bist authentifiziert!']); -}, [ - function (Request $request, callable $next) { - if ($request->getHeader('x-auth') !== 'geheim') { - return (new Response())->withJson(['error' => 'Nicht autorisiert'], 401); - } - return $next($request); - } -]); ``` +## API/CRUD-Beispiel + +Ein vollständiges Beispiel für eine kleine REST-API mit allen HTTP-Methoden: + +```php +group('/api', function ($router) { + // Alle User (GET) + $router->get('/users', function (Request $request, array $params) { + return (new Response())->withJson(['users' => ['Alice', 'Bob', 'Charlie']]); + }); + // User anlegen (POST) + $router->post('/users', function (Request $request, array $params) { + return (new Response())->withJson(['message' => 'User created'], 201); + }); + // User aktualisieren (PUT) + $router->put('/users/{id}', function (Request $request, array $params) { + return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]); + }); + // User Teil-Update (PATCH) + $router->patch('/users/{id}', function (Request $request, array $params) { + return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]); + }); + // User löschen (DELETE) + $router->delete('/users/{id}', function (Request $request, array $params) { + return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]); + }); + // OPTIONS für CORS/Preflight + $router->options('/users', function (Request $request, array $params) { + return (new Response()) + ->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS') + ->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']); + }); +}); +``` --- ## Named Routes & URL-Generator @@ -88,7 +168,6 @@ $router->get('/article/{slug}', function (Request $request, array $params) { $url = $router->url('article.show', ['slug' => 'mein-artikel']); // Ergebnis: /article/mein-artikel ``` - --- ## Route-Gruppen & Prefixes @@ -101,16 +180,19 @@ $router->group('/api', function ($router) { $router->post('/users', [UserController::class, 'create']); }); ``` - --- -## Internes Forwarding (Router::forward) +## Internes Forwarding (Router::forward) vs. Redirect -Mit `Router::forward()` kannst du innerhalb eines Handlers oder einer Middleware intern auf eine andere benannte Route weiterleiten – inklusive Übergabe von Route-Parametern und Query-Params. Der Client bekommt davon nichts mit (kein Redirect). +Mit `Router::forward()` kannst du innerhalb eines Handlers oder einer Middleware intern auf eine andere benannte Route weiterleiten – inklusive Übergabe von Route-Parametern und Query-Params. **Der Client bekommt davon nichts mit (kein Redirect, keine neue URL im Browser).** -### Beispiel +Im Gegensatz dazu erzeugt `withRedirect()` einen echten HTTP-Redirect (Status 3xx), bei dem der Client einen neuen Request an die Ziel-URL macht. + +### Beispiel für internes Forwarding ```php +withJson(['success' => true]); // HTML-Antwort @@ -210,10 +295,17 @@ function (Request $request, array $params) --- +## Insomnia-Collection +Für schnelles Testen und als API-Dokumentation liegt eine Insomnia-Collection bei: +**`example/insomnia.json`** + +- Importiere die Datei in Insomnia (oder kompatible Tools), um alle Beispiel- und API-Endpunkte direkt zu testen. +- Die Collection enthält Demo- und API-Requests, passende Header und Beispiel-Bodies. --- + ## Routen-Dokumentation - **Alle Routen als JSON:** `/routes` @@ -226,22 +318,13 @@ function (Request $request, array $params) ## Routen-Caching & CLI - - - **Cache neu bauen:** - `bin/route-cache build` - - **Cache löschen:** - `bin/route-cache clear` - - **Cache anzeigen:** - `bin/route-cache show` - - **Alle Routen auflisten:** - `bin/route-cache list` ### CLI-Tool verwenden @@ -260,7 +343,6 @@ Verfügbare Befehle: - `show` – Cache anzeigen (JSON) - `list` – Alle registrierten Routen anzeigen - --- ## Projektstruktur @@ -271,8 +353,6 @@ example/ # Demo-Anwendung (Controller, Routen, Public) bin/ # CLI-Tools cache/ # Routen-Cache (JSON) ``` - - --- @@ -344,13 +424,9 @@ $controller = $container->get(UserController::class); ## Weiterführendes - **Eigene Controller:** Lege sie unter `example/app/Controller` ab und verwende sie als Handler. - - **Middleware:** Schreibe eigene Middleware als Closure oder Klasse. - - **Tests & Erweiterungen:** Das Framework ist modular und kann leicht erweitert werden. - - --- diff --git a/bin/route-cache b/bin/route-cache index 8278ea8..be5ad13 100644 --- a/bin/route-cache +++ b/bin/route-cache @@ -1,12 +1,14 @@ #!/usr/bin/env php clear(); - echo "Route-Cache wurde gelöscht: $cacheFile\n"; + try { + $routeCache->clear(); + echo "Route-Cache wurde gelöscht: $cacheFile\n"; + } catch (Throwable $e) { + fwrite(STDERR, "Fehler beim Löschen des Caches: " . $e->getMessage() . "\n"); + exit(2); + } break; case 'build': - $router = new Router(); - require __DIR__ . '/../example/routes/web.php'; - $routeCache->write($router->routes); - echo "Route-Cache wurde neu generiert: $cacheFile\n"; + try { + $router = new Router(); + require __DIR__ . '/../example/routes/web.php'; + $routeCache->write($router->routes); + echo "Route-Cache wurde neu generiert: $cacheFile\n"; + } catch (Throwable $e) { + fwrite(STDERR, "Fehler beim Generieren des Caches: " . $e->getMessage() . "\n"); + exit(2); + } break; case 'show': - $data = $routeCache->read(); - if ($data === null) { - echo "Kein Route-Cache gefunden: $cacheFile\n"; - exit(1); + try { + $data = $routeCache->read(); + if ($data === null) { + echo "Kein Route-Cache gefunden: $cacheFile\n"; + exit(1); + } + echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n"; + } catch (Throwable $e) { + fwrite(STDERR, "Fehler beim Lesen des Caches: " . $e->getMessage() . "\n"); + exit(2); } - echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n"; break; case 'list': - $router = new Router(); - require __DIR__ . '/../example/routes/web.php'; - echo "Alle registrierten Routen:\n"; - echo str_pad("METHODE", 8) . str_pad("PFAD", 30) . str_pad("NAME", 25) . "HANDLER\n"; - echo str_repeat("-", 80) . "\n"; - foreach ($router->routes as $method => $routesArr) { - foreach ($routesArr as $pattern => $info) { - $name = $info['name'] ?? ''; - $handler = $info['handler']; - if (is_string($handler)) { - $handlerStr = $handler; - } elseif (is_array($handler)) { - if (isset($handler[0]) && isset($handler[1])) { - $handlerStr = (is_string($handler[0]) ? $handler[0] : get_class($handler[0])) . '::' . $handler[1]; + try { + $router = new Router(); + require __DIR__ . '/../example/routes/web.php'; + echo "Alle registrierten Routen:\n"; + echo str_pad("METHODE", 8) . str_pad("PFAD", 30) . str_pad("NAME", 25) . "HANDLER\n"; + echo str_repeat("-", 80) . "\n"; + foreach ($router->routes as $method => $routesArr) { + foreach ($routesArr as $pattern => $info) { + $name = $info['name'] ?? ''; + $handler = $info['handler']; + if (is_string($handler)) { + $handlerStr = $handler; + } elseif (is_array($handler)) { + if (isset($handler[0]) && isset($handler[1])) { + $handlerStr = (is_string($handler[0]) ? $handler[0] : (is_object($handler[0]) ? get_class($handler[0]) : '[Objekt]')) . '::' . $handler[1]; + } else { + $handlerStr = '[Array]'; + } + } elseif ($handler instanceof Closure) { + $handlerStr = 'Closure'; } else { - $handlerStr = '[Array]'; + $handlerStr = gettype($handler); } - } elseif ($handler instanceof Closure) { - $handlerStr = 'Closure'; - } else { - $handlerStr = gettype($handler); + echo str_pad($method, 8) . str_pad($pattern, 30) . str_pad($name, 25) . $handlerStr . "\n"; } - echo str_pad($method, 8) . str_pad($pattern, 30) . str_pad($name, 25) . $handlerStr . "\n"; } + } catch (Throwable $e) { + fwrite(STDERR, "Fehler beim Anzeigen der Routen: " . $e->getMessage() . "\n"); + exit(2); } break; diff --git a/example/app/Controller/HelloController.php b/example/app/Controller/HelloController.php index abd28e8..abc8607 100644 --- a/example/app/Controller/HelloController.php +++ b/example/app/Controller/HelloController.php @@ -5,10 +5,21 @@ namespace App\Controller; use MyCodebox\MariaCore\Http\Request; use MyCodebox\MariaCore\Http\Response; +/** + * Beispiel-Controller für Begrüßungen. + */ class HelloController { - public function greet(Request $request, array $params) + /** + * Gibt eine HTML-Begrüßung zurück. + * + * @param Request $request + * @param array $params + * @return Response + */ + public function greet(Request $request, array $params): Response { + // Name aus den Route-Parametern holen, gegen XSS absichern $name = htmlspecialchars($params['name'] ?? 'Gast'); return (new Response())->withHtml("

Hallo aus dem Controller, {$name}!

"); } diff --git a/example/app/Controller/RoutesController.php b/example/app/Controller/RoutesController.php index 99b45f3..1615945 100644 --- a/example/app/Controller/RoutesController.php +++ b/example/app/Controller/RoutesController.php @@ -5,16 +5,34 @@ namespace App\Controller; use MyCodebox\MariaCore\Http\Request; use MyCodebox\MariaCore\Http\Response; +/** + * Controller für die Anzeige und Ausgabe der registrierten Routen. + */ class RoutesController { + /** + * @var mixed Router-Instanz (typischerweise MyCodebox\MariaCore\Router) + */ protected $router; + /** + * Konstruktor. + * + * @param mixed $router + */ public function __construct($router) { $this->router = $router; } - public function json(Request $request, array $params) + /** + * Gibt alle registrierten Routen als JSON zurück. + * + * @param Request $request + * @param array $params + * @return Response + */ + public function json(Request $request, array $params): Response { $routes = []; foreach ($this->router->getRoutes() as $method => $paths) { @@ -30,7 +48,14 @@ class RoutesController return (new Response())->withJson($routes, 200, JSON_PRETTY_PRINT); } - public function html(Request $request, array $params) + /** + * Gibt alle registrierten Routen als HTML-Tabelle zurück. + * + * @param Request $request + * @param array $params + * @return Response + */ + public function html(Request $request, array $params): Response { $routes = []; foreach ($this->router->getRoutes() as $method => $paths) { @@ -45,8 +70,8 @@ class RoutesController } $html = '

Routen-Übersicht

'; foreach ($routes as $route) { - $link = '' . htmlspecialchars($route['path']) . ''; - $html .= ''; + $link = '' . htmlspecialchars($route['path'], ENT_QUOTES, 'UTF-8') . ''; + $html .= ''; } $html .= '
MethodPathNameMiddleware
' . htmlspecialchars($route['method']) . '' . $link . '' . htmlspecialchars($route['name']) . '' . $route['middleware_count'] . '
' . htmlspecialchars($route['method'], ENT_QUOTES, 'UTF-8') . '' . $link . '' . htmlspecialchars($route['name'], ENT_QUOTES, 'UTF-8') . '' . (int)$route['middleware_count'] . '
'; return (new Response())->withHtml($html); diff --git a/example/public/index.php b/example/public/index.php index b8b2b5d..65f3f48 100644 --- a/example/public/index.php +++ b/example/public/index.php @@ -1,6 +1,10 @@ addMiddleware(function (Request $request, callable $next) { - // Beispiel: Logging - error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri()); + // Logging-Beispiel + error_log('[Router] ' . $request->getMethod() . ' ' . $request->getUri()); // Weiter zur nächsten Middleware/Handler return $next($request); }); -// Beispiel: Custom Error Handler +// Custom Error Handler (gibt Fehler als JSON zurück) $router->setErrorHandler(function (Request $request, Throwable $e) { - // Beispiel: Gib Fehler als JSON zurück, mit Status 500 return (new Response())->withJson([ 'error' => 'Fehler im Router', 'message' => $e->getMessage(), @@ -29,7 +32,9 @@ $router->setErrorHandler(function (Request $request, Throwable $e) { ], 500); }); -// Immer web.php laden (alle Routen, inkl. Closures) +// ------------------------------------------------- +// Routen registrieren (immer web.php laden) +// ------------------------------------------------- require __DIR__ . '/../routes/web.php'; // Nach dem Registrieren aller Routen: cachebare Infos extrahieren und speichern diff --git a/example/routes/web.php b/example/routes/web.php index 57eb37b..ac34580 100644 --- a/example/routes/web.php +++ b/example/routes/web.php @@ -6,22 +6,21 @@ use MyCodebox\MariaCore\Http\Response; use App\Controller\HelloController; use App\Controller\RoutesController; +// --------------------------------------------------- // Controller-Instanzen erzeugen +// --------------------------------------------------- $routesController = new RoutesController($router); +// --------------------------------------------------- // GET-Routen +// --------------------------------------------------- $router->get('/', function (Request $request, array $params) { return (new Response())->withHtml('

Willkommen auf der Startseite!

'); }); - $router->get('/routes', [$routesController, 'json']); - - - $router->get('/routes.html', [$routesController, 'html']); - $router->get('/protected', function (Request $request, array $params) { return (new Response())->withJson(['message' => 'Du bist authentifiziert!']); }, [ @@ -44,9 +43,7 @@ $router->get('/user/{id}', function (Request $request, array $params) use ($rout ]); })->name('user.profile'); - $router->get('/go-home', function (Request $request, array $params) { - return (new Response())->withRedirect('/'); }); @@ -56,7 +53,6 @@ $router->get('/forward-demo', function (Request $request, array $params) use ($r return $router->forward('user.profile', ['id' => 99], ['foo' => 'bar']); }); - $router->get('/plain', function (Request $request, array $params) { return (new Response())->withText("Dies ist eine reine Textantwort."); }); @@ -66,7 +62,9 @@ $router->get('/download', function (Request $request, array $params) { return (new Response())->withDownload('beispiel.txt', $content, 'text/plain'); }); +// --------------------------------------------------- // POST-Routen +// --------------------------------------------------- $router->post('/users', function (Request $request, array $params) { return (new Response())->withJson(['message' => 'User created'], 201); }); @@ -77,27 +75,39 @@ $router->post('/submit', function (Request $request, array $params) { return (new Response())->withHtml("

Formular empfangen, Name: {$name}

"); }); +// --------------------------------------------------- // PUT-Routen +// --------------------------------------------------- $router->put('/users/{id}', function (Request $request, array $params) { return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]); }); +// --------------------------------------------------- // PATCH-Routen +// --------------------------------------------------- $router->patch('/users/{id}', function (Request $request, array $params) { return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]); }); +// --------------------------------------------------- // DELETE-Routen +// --------------------------------------------------- $router->delete('/users/{id}', function (Request $request, array $params) { return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]); }); +// --------------------------------------------------- // OPTIONS-Routen +// --------------------------------------------------- $router->options('/users', function (Request $request, array $params) { - return (new Response())->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']); + return (new Response()) + ->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS') + ->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']); }); -// Beispiel für Route-Gruppen und Prefixes +// --------------------------------------------------- +// Beispiel für Route-Gruppen und Prefixes (API) +// --------------------------------------------------- $router->group('/api', function ($router) { $router->get('/users', function (Request $request, array $params) { return (new Response())->withJson(['users' => ['Alice', 'Bob', 'Charlie']]); @@ -115,15 +125,17 @@ $router->group('/api', function ($router) { return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]); }); $router->options('/users', function (Request $request, array $params) { - return (new Response())->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']); + return (new Response()) + ->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS') + ->withJson(['allow' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS']); }); - // Ergänzung: PATCH /api/users (Demo-Response für Teil-Update aller User) + // PATCH /api/users (Demo-Response für Teil-Update aller User) $router->patch('/users', function (Request $request, array $params) { return (new Response())->withJson([ 'message' => 'Alle User wurden (demo) teilweise aktualisiert.' ]); }); - // Ergänzung: GET /api/users/{id} + // GET /api/users/{id} $router->get('/users/{id}', function (Request $request, array $params) use ($router) { $id = $params['id'] ?? null; $profileUrl = $router->url('user.profile', ['id' => $id]); @@ -132,7 +144,7 @@ $router->group('/api', function ($router) { 'profile_url' => $profileUrl ]); }); - // Ergänzung: OPTIONS /api/users/{id} + // OPTIONS /api/users/{id} $router->options('/users/{id}', function (Request $request, array $params) { return (new Response()) ->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS') @@ -140,6 +152,9 @@ $router->group('/api', function ($router) { }); }); +// --------------------------------------------------- +// Beispiel für Route-Gruppen und Prefixes (Admin) +// --------------------------------------------------- $router->group('/admin', function ($router) { $router->get('/dashboard', function (Request $request, array $params) { return (new Response())->withJson(['dashboard' => 'Admin stats here']); diff --git a/src/Cache/RouteCache.php b/src/Cache/RouteCache.php index 4be61bc..d5dc686 100644 --- a/src/Cache/RouteCache.php +++ b/src/Cache/RouteCache.php @@ -3,13 +3,16 @@ namespace MyCodebox\MariaCore\Cache; /** - * RouteCache + * Class RouteCache * * Verwaltet das Caching der Routen-Metadaten als JSON-Datei. * Cacht nur serialisierbare Handler (Strings, Controller-Arrays), keine Closures! */ class RouteCache { + /** + * @var string Pfad zur Cache-Datei + */ private string $cacheFile; /** @@ -52,12 +55,17 @@ class RouteCache } } if (!is_dir(dirname($this->cacheFile))) { - mkdir(dirname($this->cacheFile), 0777, true); + if (!@mkdir(dirname($this->cacheFile), 0777, true) && !is_dir(dirname($this->cacheFile))) { + throw new \RuntimeException('Cache-Verzeichnis konnte nicht erstellt werden: ' . dirname($this->cacheFile)); + } + } + $json = json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); + if ($json === false) { + throw new \RuntimeException('Fehler beim Serialisieren der Routen für den Cache.'); + } + if (@file_put_contents($this->cacheFile, $json) === false) { + throw new \RuntimeException('Cache-Datei konnte nicht geschrieben werden: ' . $this->cacheFile); } - file_put_contents( - $this->cacheFile, - json_encode($cache, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) - ); } /** @@ -70,7 +78,15 @@ class RouteCache if (!file_exists($this->cacheFile)) { return null; } - return json_decode(file_get_contents($this->cacheFile), true); + $content = @file_get_contents($this->cacheFile); + if ($content === false) { + throw new \RuntimeException('Cache-Datei konnte nicht gelesen werden: ' . $this->cacheFile); + } + $data = json_decode($content, true); + if ($data === null && json_last_error() !== JSON_ERROR_NONE) { + throw new \RuntimeException('Fehler beim Parsen der Cache-Datei: ' . json_last_error_msg()); + } + return $data; } /** @@ -81,7 +97,9 @@ class RouteCache public function clear(): void { if (file_exists($this->cacheFile)) { - unlink($this->cacheFile); + if (!@unlink($this->cacheFile)) { + throw new \RuntimeException('Cache-Datei konnte nicht gelöscht werden: ' . $this->cacheFile); + } } } } diff --git a/src/Http/Request.php b/src/Http/Request.php index c1dda40..89bf720 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -4,6 +4,12 @@ namespace MyCodebox\MariaCore\Http; /** * Simplified PSR-7-inspired Request class. + * + * @property string $method + * @property string $uri + * @property array $queryParams + * @property array $parsedBody + * @property array $headers */ class Request { @@ -13,6 +19,11 @@ class Request protected array $parsedBody; protected array $headers; + /** + * Request constructor. + * + * Initializes the request object from PHP globals. + */ public function __construct() { $this->method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; @@ -24,6 +35,8 @@ class Request /** * Get the HTTP method. + * + * @return string */ public function getMethod(): string { @@ -32,6 +45,8 @@ class Request /** * Get the URI path. + * + * @return string */ public function getUri(): string { @@ -40,6 +55,8 @@ class Request /** * Get query parameters. + * + * @return array */ public function getQueryParams(): array { @@ -48,6 +65,8 @@ class Request /** * Get parsed body parameters (POST data). + * + * @return array */ public function getParsedBody(): array { @@ -56,6 +75,9 @@ class Request /** * Get all HTTP headers as an associative array. + * Header-Namen sind immer klein geschrieben. + * + * @return array */ public function getHeaders(): array { @@ -64,20 +86,19 @@ class Request /** * Get a specific header value or null if not found. + * Der Header-Name ist case-insensitive. + * + * @param string $name + * @return string|null */ public function getHeader(string $name): ?string { $name = strtolower($name); - foreach ($this->headers as $key => $value) { - if (strtolower($key) === $name) { - return $value; - } - } - return null; + return $this->headers[$name] ?? null; } /** - * Erzeuge ein Request-Objekt mit beliebigen Parametern (für internes Forwarding). + * Create a Request object with custom parameters (for internal forwarding). * * @param array $override ['method' => ..., 'uri' => ..., 'queryParams' => ..., 'parsedBody' => ..., 'headers' => ...] * @return static @@ -98,26 +119,28 @@ class Request $instance->parsedBody = $override['parsedBody']; } if (isset($override['headers'])) { - $instance->headers = $override['headers']; + // Vereinheitliche Header-Namen auf Kleinbuchstaben + $headers = []; + foreach ($override['headers'] as $key => $value) { + $headers[strtolower($key)] = $value; + } + $instance->headers = $headers; } return $instance; } - /** - * Erzeuge ein Request-Objekt mit beliebigen Parametern (für internes Forwarding). - * - * @param array $override ['method' => ..., 'uri' => ..., 'queryParams' => ..., 'parsedBody' => ..., 'headers' => ...] - - /** * Parse all HTTP headers from $_SERVER. + * Header-Namen werden als Kleinbuchstaben gespeichert. + * + * @return array */ protected function parseHeaders(): array { $headers = []; foreach ($_SERVER as $key => $value) { if (str_starts_with($key, 'HTTP_')) { - $header = str_replace('_', '-', strtolower(substr($key, 5))); + $header = strtolower(str_replace('_', '-', substr($key, 5))); $headers[$header] = $value; } } diff --git a/src/Http/Response.php b/src/Http/Response.php index 3ce70ed..85e311b 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -179,14 +179,21 @@ class Response /** * Return a new response with JSON body and appropriate content type. * - * @param mixed $data - * @param int $statusCode - * @param int $jsonOptions + * @param mixed $data Data to encode as JSON + * @param int $statusCode HTTP status code + * @param int $jsonOptions JSON encoding options * @return self */ public function withJson(mixed $data, int $statusCode = 200, int $jsonOptions = 0): self { $body = json_encode($data, $jsonOptions | JSON_UNESCAPED_UNICODE); + if ($body === false) { + $body = json_encode([ + 'error' => 'JSON encoding failed', + 'message' => json_last_error_msg(), + ]); + $statusCode = 500; + } $clone = clone $this; $clone->body = $body; $clone->statusCode = $statusCode; diff --git a/src/Router.php b/src/Router.php index ac9dd3b..1f281a9 100644 --- a/src/Router.php +++ b/src/Router.php @@ -8,12 +8,12 @@ use MyCodebox\MariaCore\Http\Response; /** * Class Router * - * Lightweight PSR-inspired router with middleware, route groups, named routes, and controller support. + * Leichtgewichtiger, PSR-inspirierter Router mit Middleware, Route-Gruppen, Named Routes und Controller-Support. */ class Router { /** - * All registered routes, grouped by HTTP method. + * Registrierte Routen, gruppiert nach HTTP-Methode. * @var array */ public array $routes = [ @@ -23,35 +23,35 @@ class Router 'PATCH' => [], 'DELETE' => [], 'OPTIONS' => [], - // Weitere HTTP-Methoden können hier hinzugefügt werden + // Weitere HTTP-Methoden können hier ergänzt werden ]; /** - * Named routes for URL generation. + * Benannte Routen für URL-Generierung. * @var array */ public array $namedRoutes = []; /** - * Stack for route groups (prefixes and middleware). + * Stack für Route-Gruppen (Prefix & Middleware). * @var array */ private array $groupStack = []; /** - * Global middleware applied to every route. + * Globale Middleware, die auf jede Route angewendet wird. * @var callable[] */ private array $globalMiddleware = []; /** - * Register a route with optional middleware. + * Registriert eine Route mit optionaler Middleware. * * @param string $method * @param string $pattern * @param callable|string|array $handler * @param array $middleware - * @return object RouteRegistrar for method chaining (->name()) + * @return object RouteRegistrar für Method-Chaining (->name()) */ public function add(string $method, string $pattern, callable|string|array $handler, array $middleware = []) { @@ -72,7 +72,7 @@ class Router 'name' => null, ]; - // Return a RouteRegistrar object for method chaining (e.g. ->name()) + // RouteRegistrar für ->name() return new class($this, $method, $pattern) { private $router; private $method; @@ -92,61 +92,47 @@ class Router }; } - /** - * Register a GET route. - */ + /** GET-Route registrieren. */ public function get(string $pattern, callable|string|array $handler, array $middleware = []) { return $this->add('GET', $pattern, $handler, $middleware); } - /** - * Register a POST route. - */ + /** POST-Route registrieren. */ public function post(string $pattern, callable|string|array $handler, array $middleware = []) { return $this->add('POST', $pattern, $handler, $middleware); } - /** - * Register a PUT route. - */ + /** PUT-Route registrieren. */ public function put(string $pattern, callable|string|array $handler, array $middleware = []) { return $this->add('PUT', $pattern, $handler, $middleware); } - /** - * Register a PATCH route. - */ + /** PATCH-Route registrieren. */ public function patch(string $pattern, callable|string|array $handler, array $middleware = []) { return $this->add('PATCH', $pattern, $handler, $middleware); } - /** - * Register a DELETE route. - */ + /** DELETE-Route registrieren. */ public function delete(string $pattern, callable|string|array $handler, array $middleware = []) { return $this->add('DELETE', $pattern, $handler, $middleware); } - /** - * Register an OPTIONS route. - */ + /** OPTIONS-Route registrieren. */ public function options(string $pattern, callable|string|array $handler, array $middleware = []) { return $this->add('OPTIONS', $pattern, $handler, $middleware); } - /** - * @var callable|null - */ + /** @var callable|null */ private $errorHandler = null; /** - * Set a global error handler. + * Setzt einen globalen Error-Handler. * @param callable $handler function(Request $request, \Throwable $e): Response */ public function setErrorHandler(callable $handler): void @@ -155,7 +141,7 @@ class Router } /** - * Dispatch the router for the given request. + * Dispatcht den Router für den gegebenen Request. * * @param Request $request * @return Response @@ -175,7 +161,7 @@ class Router $regex = $this->convertPatternToRegex($pattern, $params); if (preg_match($regex, $uri, $matches)) { - // Extract parameters + // Parameter extrahieren $params = []; foreach ($matches as $key => $value) { if (!is_int($key)) { @@ -186,36 +172,47 @@ class Router $handler = $route['handler']; $routeMiddleware = $route['middleware'] ?? []; - // Build middleware stack + // Middleware-Stack bauen $middlewareStack = array_merge( $this->globalMiddleware, $routeMiddleware, [ function ($request) use ($handler, $params) { - // Controller support: "Controller@method" or [ControllerClass, method] + // Controller-Support: "Controller@method" oder [ControllerClass, method] if (is_string($handler) && strpos($handler, '@') !== false) { [$class, $method] = explode('@', $handler, 2); if (class_exists($class)) { $controller = new $class(); - return $controller->$method($request, $params); + if (method_exists($controller, $method)) { + return $controller->$method($request, $params); + } + throw new \RuntimeException("Methode $method nicht gefunden in Controller $class."); } + throw new \RuntimeException("Controller-Klasse $class nicht gefunden."); } if (is_array($handler) && count($handler) === 2 && is_string($handler[0])) { if (class_exists($handler[0])) { $controller = new $handler[0](); $method = $handler[1]; - return $controller->$method($request, $params); + if (method_exists($controller, $method)) { + return $controller->$method($request, $params); + } + throw new \RuntimeException("Methode $method nicht gefunden in Controller {$handler[0]}."); } + throw new \RuntimeException("Controller-Klasse {$handler[0]} nicht gefunden."); } - return call_user_func($handler, $request, $params); + if (is_callable($handler)) { + return call_user_func($handler, $request, $params); + } + throw new \RuntimeException('Ungültiger Route-Handler.'); } ] ); - // Run middleware stack + // Middleware-Stack ausführen $runner = function ($request, $middlewareStack, $index = 0) use (&$runner) { if (!isset($middlewareStack[$index])) { - throw new \RuntimeException('Middleware stack exhausted with no response.'); + throw new \RuntimeException('Kein Response-Objekt aus Middleware-Stack zurückgegeben.'); } $middleware = $middlewareStack[$index]; return $middleware($request, function ($req) use ($runner, $middlewareStack, $index) { @@ -232,7 +229,7 @@ class Router if ($this->errorHandler) { return call_user_func($this->errorHandler, $request, $e); } - // Fallback: Standard error output + // Fallback: Standard-Fehlerausgabe return (new Response())->withJson([ 'error' => 'Internal Server Error', 'message' => $e->getMessage() @@ -241,7 +238,7 @@ class Router } /** - * Get all registered routes. + * Gibt alle registrierten Routen zurück. * * @return array */ @@ -251,7 +248,7 @@ class Router } /** - * Group routes under a common prefix and/or middleware. + * Gruppiert Routen unter einem gemeinsamen Prefix und/oder Middleware. * * @param string $prefix * @param callable $callback @@ -268,9 +265,7 @@ class Router array_pop($this->groupStack); } - /** - * Register a named route (internal use). - */ + /** Benannte Route registrieren (intern). */ public function nameRoute(string $name, string $method, string $pattern): void { $this->namedRoutes[$name] = [ @@ -280,7 +275,7 @@ class Router } /** - * Generate a URL for a named route and parameters. + * Generiert eine URL für eine benannte Route und Parameter. * * @param string $name * @param array $params @@ -292,7 +287,7 @@ class Router return null; } $pattern = $this->namedRoutes[$name]['pattern']; - // Replace placeholders in pattern with parameters + // Platzhalter im Pattern durch Parameter ersetzen $url = preg_replace_callback('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', function ($matches) use (&$params) { $key = $matches[1]; if (isset($params[$key])) { @@ -302,7 +297,7 @@ class Router } return $matches[0]; }, $pattern); - // Add remaining params as query string + // Übrige Parameter als Query-String anhängen if (!empty($params)) { $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params); } @@ -310,7 +305,7 @@ class Router } /** - * Add global middleware. + * Globale Middleware hinzufügen. * * @param callable $middleware * @return void @@ -320,9 +315,7 @@ class Router $this->globalMiddleware[] = $middleware; } - /** - * Get current prefix from group stack. - */ + /** Liefert aktuellen Prefix aus dem Group-Stack. */ private function getCurrentPrefix(): string { $prefix = ''; @@ -332,9 +325,7 @@ class Router return $prefix; } - /** - * Get all middleware from group stack. - */ + /** Liefert alle Middleware aus dem Group-Stack. */ private function getCurrentGroupMiddleware(): array { $all = []; @@ -347,9 +338,9 @@ class Router } /** - * Convert a route pattern to regex and extract parameter names. + * Wandelt ein Routen-Pattern in Regex um und extrahiert Parameternamen. * - * Example: /user/{id} => #^/user/(?P[^/]+)$# + * Beispiel: /user/{id} => #^/user/(?P[^/]+)$# * * @param string $pattern * @param array &$params @@ -357,7 +348,7 @@ class Router */ private function convertPatternToRegex(string $pattern, array &$params): string { - // Allow constraints: {param:regex} + // Constraints erlauben: {param:regex} $regex = preg_replace_callback( '#\{([a-zA-Z_][a-zA-Z0-9_]*)(:([^}]+))?\}#', function ($matches) use (&$params) { @@ -371,7 +362,7 @@ class Router } /** - * Internally forward to another named route, optionally with parameters and query params. + * Internes Forwarding auf eine andere benannte Route (ohne HTTP-Redirect). * * @param string $routeName * @param array $params