Refactor: Controller ausgelagert, RouteController umbenannt und Links in /routes.html hinzugefügt
This commit is contained in:
parent
f3b65e02c9
commit
a3f8638d54
9 changed files with 734 additions and 44 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -2,6 +2,9 @@
|
|||
/vendor/
|
||||
/composer.lock
|
||||
|
||||
# Cache
|
||||
/cache/
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
|
|
|||
54
AGENDS.md
Normal file
54
AGENDS.md
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
# AGENDS.md
|
||||
|
||||
## Aufgaben & ToDos für MariaCore Router-Framework
|
||||
|
||||
### Geplante Features
|
||||
|
||||
1. **Middleware-Unterstützung**
|
||||
- Globale Middleware
|
||||
- Routen-spezifische Middleware
|
||||
|
||||
2. **Route-Gruppen und Prefixes**
|
||||
- Gruppierung von Routen mit gemeinsamen Prefixes und/oder Middleware
|
||||
|
||||
3. **HTTP-Methoden erweitern**
|
||||
- Unterstützung für PUT, DELETE, PATCH, OPTIONS
|
||||
|
||||
4. **Named Routes & URL-Generator**
|
||||
- Routen können benannt werden
|
||||
- URLs können anhand des Namens generiert werden
|
||||
|
||||
5. **Parameter-Validierung & Constraints**
|
||||
- Parameter können mit Regex validiert werden
|
||||
|
||||
6. **Error Handling & Custom Error Pages**
|
||||
- Zentrale Fehlerbehandlung, eigene Fehlerseiten/JSON
|
||||
|
||||
7. **Request- und Response-Helper**
|
||||
- Methoden wie withRedirect, withHtml, withText, withDownload
|
||||
|
||||
8. **Controller-Support**
|
||||
- Handler können auch als Controller@Methode angegeben werden
|
||||
|
||||
9. **Routen-Caching**
|
||||
- Optional: Routenstruktur als Cache speichern und laden
|
||||
|
||||
10. **Routen-Dokumentation**
|
||||
- Automatische Übersicht aller Routen als HTML oder JSON
|
||||
|
||||
---
|
||||
|
||||
### Notizen
|
||||
|
||||
- Die Reihenfolge der Implementierung kann je nach Komplexität und Abhängigkeiten angepasst werden.
|
||||
- Nach jedem Feature-Block erfolgt ein kurzer Test und eine Dokumentation im AGENDS.md.
|
||||
- Bei größeren Änderungen: Branch-Strategie beachten (dev, test, main).
|
||||
|
||||
---
|
||||
|
||||
### Sonstiges
|
||||
|
||||
- Ideen, Bugs, Refactoring-Vorschläge oder offene Fragen können hier ebenfalls notiert werden.
|
||||
- Für Feedback und Review: Siehe Git-Commits und Pull Requests.
|
||||
|
||||
---
|
||||
|
|
@ -10,21 +10,34 @@ use MyCodebox\MariaCore\Router;
|
|||
// Router-Instanz erstellen
|
||||
$router = new Router();
|
||||
|
||||
// Beispielrouten registrieren
|
||||
$router->get('/', function (Request $request, array $params) {
|
||||
return new Response('<h1>Willkommen auf der Startseite!</h1>');
|
||||
// Beispiel: Routen-Caching verwenden
|
||||
$cacheFile = __DIR__ . '/../cache/routes.cache.php';
|
||||
|
||||
// Wenn Cache existiert, lade ihn, sonst speichere nach Registrierung der Routen
|
||||
if (file_exists($cacheFile)) {
|
||||
$router->loadCachedRoutes($cacheFile);
|
||||
}
|
||||
|
||||
// Beispiel: Globale Middleware (wird bei jedem Request ausgeführt)
|
||||
$router->addMiddleware(function (Request $request, callable $next) {
|
||||
// Beispiel: Logging
|
||||
error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri());
|
||||
// Weiter zur nächsten Middleware/Handler
|
||||
return $next($request);
|
||||
});
|
||||
|
||||
$router->get('/hello/{name}', function (Request $request, array $params) {
|
||||
$name = htmlspecialchars($params['name'] ?? 'Gast');
|
||||
return new Response("<h1>Hallo, {$name}!</h1>");
|
||||
// Beispiel: Custom Error Handler
|
||||
$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(),
|
||||
'route' => $request->getUri()
|
||||
], 500);
|
||||
});
|
||||
|
||||
$router->post('/submit', function (Request $request, array $params) {
|
||||
$data = $request->getParsedBody();
|
||||
$name = htmlspecialchars($data['name'] ?? 'Unbekannt');
|
||||
return new Response("<h1>Formular empfangen, Name: {$name}</h1>");
|
||||
});
|
||||
// Routendefinitionen dynamisch laden
|
||||
require __DIR__ . '/../routes/web.php';
|
||||
|
||||
// Request erzeugen und dispatchen
|
||||
$request = new Request();
|
||||
|
|
|
|||
120
routes/web.php
Normal file
120
routes/web.php
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
|
||||
<?php
|
||||
|
||||
use MyCodebox\MariaCore\Http\Request;
|
||||
use MyCodebox\MariaCore\Http\Response;
|
||||
use MyCodebox\MariaCore\Controller\HelloController;
|
||||
use MyCodebox\MariaCore\Controller\RouteController;
|
||||
|
||||
// Controller-Instanzen erzeugen
|
||||
$routeController = new RouteController($router);
|
||||
|
||||
// GET-Routen
|
||||
$router->get('/', function (Request $request, array $params) {
|
||||
return (new Response())->withHtml('<h1>Willkommen auf der Startseite!</h1>');
|
||||
});
|
||||
|
||||
$router->get('/routes', [$routeController, 'json']);
|
||||
|
||||
$router->get('/routes.html', [$routeController, 'html']);
|
||||
|
||||
$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);
|
||||
}
|
||||
]);
|
||||
|
||||
$router->get('/hello/{name}', [HelloController::class, 'greet'])->name('hello');
|
||||
|
||||
$router->get('/user/{id}', function (Request $request, array $params) use ($router) {
|
||||
$id = $params['id'] ?? null;
|
||||
$profileUrl = $router->url('user.profile', ['id' => $id]);
|
||||
return (new Response())->withJson([
|
||||
'user_id' => $id,
|
||||
'profile_url' => $profileUrl
|
||||
]);
|
||||
})->name('user.profile');
|
||||
|
||||
$router->get('/go-home', function (Request $request, array $params) {
|
||||
return (new Response())->withRedirect('/');
|
||||
});
|
||||
|
||||
$router->get('/plain', function (Request $request, array $params) {
|
||||
return (new Response())->withText("Dies ist eine reine Textantwort.");
|
||||
});
|
||||
|
||||
$router->get('/download', function (Request $request, array $params) {
|
||||
$content = "Dies ist der Inhalt der Datei.\nViel Spaß!";
|
||||
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);
|
||||
});
|
||||
|
||||
$router->post('/submit', function (Request $request, array $params) {
|
||||
$data = $request->getParsedBody();
|
||||
$name = htmlspecialchars($data['name'] ?? 'Unbekannt');
|
||||
return (new Response())->withHtml("<h1>Formular empfangen, Name: {$name}</h1>");
|
||||
});
|
||||
|
||||
// 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']);
|
||||
});
|
||||
|
||||
// Beispiel für Route-Gruppen und Prefixes
|
||||
$router->group('/api', function ($router) {
|
||||
$router->get('/users', function (Request $request, array $params) {
|
||||
return (new Response())->withJson(['users' => ['Alice', 'Bob', 'Charlie']]);
|
||||
});
|
||||
$router->post('/users', function (Request $request, array $params) {
|
||||
return (new Response())->withJson(['message' => 'User created'], 201);
|
||||
});
|
||||
$router->put('/users/{id}', function (Request $request, array $params) {
|
||||
return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]);
|
||||
});
|
||||
$router->patch('/users/{id}', function (Request $request, array $params) {
|
||||
return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]);
|
||||
});
|
||||
$router->delete('/users/{id}', function (Request $request, array $params) {
|
||||
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']);
|
||||
});
|
||||
});
|
||||
|
||||
$router->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);
|
||||
}
|
||||
]);
|
||||
15
src/Controller/HelloController.php
Normal file
15
src/Controller/HelloController.php
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<?php
|
||||
|
||||
namespace MyCodebox\MariaCore\Controller;
|
||||
|
||||
use MyCodebox\MariaCore\Http\Request;
|
||||
use MyCodebox\MariaCore\Http\Response;
|
||||
|
||||
class HelloController
|
||||
{
|
||||
public function greet(Request $request, array $params)
|
||||
{
|
||||
$name = htmlspecialchars($params['name'] ?? 'Gast');
|
||||
return (new Response())->withHtml("<h1>Hallo aus dem Controller, {$name}!</h1>");
|
||||
}
|
||||
}
|
||||
54
src/Controller/RouteController.php
Normal file
54
src/Controller/RouteController.php
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
|
||||
namespace MyCodebox\MariaCore\Controller;
|
||||
|
||||
use MyCodebox\MariaCore\Http\Request;
|
||||
use MyCodebox\MariaCore\Http\Response;
|
||||
|
||||
class RouteController
|
||||
{
|
||||
protected $router;
|
||||
|
||||
public function __construct($router)
|
||||
{
|
||||
$this->router = $router;
|
||||
}
|
||||
|
||||
public function json(Request $request, array $params)
|
||||
{
|
||||
$routes = [];
|
||||
foreach ($this->router->getRoutes() as $method => $paths) {
|
||||
foreach ($paths as $path => $route) {
|
||||
$routes[] = [
|
||||
'method' => $method,
|
||||
'path' => $path,
|
||||
'name' => $route['name'] ?? null,
|
||||
'middleware_count' => isset($route['middleware']) ? count($route['middleware']) : 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
return (new Response())->withJson($routes, 200, JSON_PRETTY_PRINT);
|
||||
}
|
||||
|
||||
public function html(Request $request, array $params)
|
||||
{
|
||||
$routes = [];
|
||||
foreach ($this->router->getRoutes() as $method => $paths) {
|
||||
foreach ($paths as $path => $route) {
|
||||
$routes[] = [
|
||||
'method' => $method,
|
||||
'path' => $path,
|
||||
'name' => $route['name'] ?? '',
|
||||
'middleware_count' => isset($route['middleware']) ? count($route['middleware']) : 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
$html = '<h1>Routen-Übersicht</h1><table border="1" cellpadding="5" style="border-collapse:collapse"><tr><th>Method</th><th>Path</th><th>Name</th><th>Middleware</th></tr>';
|
||||
foreach ($routes as $route) {
|
||||
$link = '<a href="' . htmlspecialchars($route['path']) . '">' . htmlspecialchars($route['path']) . '</a>';
|
||||
$html .= '<tr><td>' . htmlspecialchars($route['method']) . '</td><td>' . $link . '</td><td>' . htmlspecialchars($route['name']) . '</td><td>' . $route['middleware_count'] . '</td></tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
return (new Response())->withHtml($html);
|
||||
}
|
||||
}
|
||||
|
|
@ -22,31 +22,49 @@ class Request
|
|||
$this->headers = $this->parseHeaders();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt die HTTP-Methode zurück.
|
||||
*/
|
||||
public function getMethod(): string
|
||||
{
|
||||
return $this->method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt die URI (Pfad) zurück.
|
||||
*/
|
||||
public function getUri(): string
|
||||
{
|
||||
return $this->uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt die Query-Parameter zurück.
|
||||
*/
|
||||
public function getQueryParams(): array
|
||||
{
|
||||
return $this->queryParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt die geparsten Body-Parameter zurück (POST-Daten).
|
||||
*/
|
||||
public function getParsedBody(): array
|
||||
{
|
||||
return $this->parsedBody;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt alle HTTP-Header als Array zurück.
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt einen bestimmten Header zurück (oder null).
|
||||
*/
|
||||
public function getHeader(string $name): ?string
|
||||
{
|
||||
$name = strtolower($name);
|
||||
|
|
@ -58,6 +76,9 @@ class Request
|
|||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Liest alle HTTP-Header aus $_SERVER.
|
||||
*/
|
||||
protected function parseHeaders(): array
|
||||
{
|
||||
$headers = [];
|
||||
|
|
|
|||
|
|
@ -8,6 +8,9 @@ class Response
|
|||
protected array $headers = [];
|
||||
protected string $body = '';
|
||||
|
||||
/**
|
||||
* Konstruktor für Response.
|
||||
*/
|
||||
public function __construct(string $body = '', int $statusCode = 200, array $headers = [])
|
||||
{
|
||||
$this->body = $body;
|
||||
|
|
@ -15,11 +18,17 @@ class Response
|
|||
$this->headers = $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt den HTTP-Statuscode zurück.
|
||||
*/
|
||||
public function getStatusCode(): int
|
||||
{
|
||||
return $this->statusCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit geändertem Statuscode zurück.
|
||||
*/
|
||||
public function withStatus(int $code): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
|
|
@ -27,11 +36,17 @@ class Response
|
|||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt alle Header als Array zurück.
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit zusätzlichem Header zurück.
|
||||
*/
|
||||
public function withHeader(string $name, string $value): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
|
|
@ -39,11 +54,17 @@ class Response
|
|||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt den Body zurück.
|
||||
*/
|
||||
public function getBody(): string
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit geändertem Body zurück.
|
||||
*/
|
||||
public function withBody(string $body): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
|
|
@ -51,6 +72,9 @@ class Response
|
|||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sendet die Response an den Client.
|
||||
*/
|
||||
public function send(): void
|
||||
{
|
||||
http_response_code($this->statusCode);
|
||||
|
|
@ -59,4 +83,65 @@ class Response
|
|||
}
|
||||
echo $this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit Redirect-Header zurück.
|
||||
*/
|
||||
public function withRedirect(string $location, int $statusCode = 302): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->statusCode = $statusCode;
|
||||
$clone->headers['Location'] = $location;
|
||||
$clone->body = '';
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit HTML-Content-Type zurück.
|
||||
*/
|
||||
public function withHtml(string $html, int $statusCode = 200): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->body = $html;
|
||||
$clone->statusCode = $statusCode;
|
||||
$clone->headers['Content-Type'] = 'text/html; charset=utf-8';
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit Text-Content-Type zurück.
|
||||
*/
|
||||
public function withText(string $text, int $statusCode = 200): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->body = $text;
|
||||
$clone->statusCode = $statusCode;
|
||||
$clone->headers['Content-Type'] = 'text/plain; charset=utf-8';
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response für Datei-Download zurück.
|
||||
*/
|
||||
public function withDownload(string $filename, string $content, string $contentType = 'application/octet-stream'): self
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->body = $content;
|
||||
$clone->headers['Content-Type'] = $contentType;
|
||||
$clone->headers['Content-Disposition'] = 'attachment; filename="' . basename($filename) . '"';
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt eine neue Response mit JSON-Body und passendem Content-Type zurück.
|
||||
*/
|
||||
public function withJson($data, int $statusCode = 200, int $jsonOptions = 0): self
|
||||
{
|
||||
$body = json_encode($data, $jsonOptions | JSON_UNESCAPED_UNICODE);
|
||||
$clone = clone $this;
|
||||
$clone->body = $body;
|
||||
$clone->statusCode = $statusCode;
|
||||
$clone->headers['Content-Type'] = 'application/json';
|
||||
return $clone;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
359
src/Router.php
359
src/Router.php
|
|
@ -10,45 +10,147 @@ class Router
|
|||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $routes = [
|
||||
public $routes = [
|
||||
'GET' => [],
|
||||
'POST' => [],
|
||||
'PUT' => [],
|
||||
'PATCH' => [],
|
||||
'DELETE' => [],
|
||||
'OPTIONS' => [],
|
||||
// Weitere Methoden können ergänzt werden
|
||||
];
|
||||
|
||||
/**
|
||||
* Route registrieren
|
||||
* @var bool
|
||||
*/
|
||||
private $routesAreCached = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var array<string, array{method: string, pattern: string}>
|
||||
*/
|
||||
public array $namedRoutes = [];
|
||||
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private array $groupStack = [];
|
||||
|
||||
/**
|
||||
* @var callable[]
|
||||
*/
|
||||
private array $globalMiddleware = [];
|
||||
|
||||
/**
|
||||
* Route registrieren, optional mit Middleware
|
||||
*
|
||||
* @param string $method
|
||||
* @param string $pattern
|
||||
* @param callable $handler
|
||||
* @param array $middleware
|
||||
*/
|
||||
public function add(string $method, string $pattern, callable $handler)
|
||||
public function add(string $method, string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
$method = strtoupper($method);
|
||||
$this->routes[$method][$pattern] = $handler;
|
||||
|
||||
$prefix = $this->getCurrentPrefix();
|
||||
$pattern = $prefix . $pattern;
|
||||
if ($pattern === '') {
|
||||
$pattern = '/';
|
||||
}
|
||||
|
||||
$groupMiddleware = $this->getCurrentGroupMiddleware();
|
||||
$allMiddleware = array_merge($groupMiddleware, $middleware);
|
||||
|
||||
$this->routes[$method][$pattern] = [
|
||||
'handler' => $handler,
|
||||
'middleware' => $allMiddleware,
|
||||
'name' => null,
|
||||
];
|
||||
|
||||
// Rückgabe eines RouteRegistrar-Objekts für method chaining (z.B. ->name())
|
||||
return new class($this, $method, $pattern) {
|
||||
private $router;
|
||||
private $method;
|
||||
private $pattern;
|
||||
public function __construct($router, $method, $pattern)
|
||||
{
|
||||
$this->router = $router;
|
||||
$this->method = $method;
|
||||
$this->pattern = $pattern;
|
||||
}
|
||||
public function name(string $name)
|
||||
{
|
||||
$this->router->nameRoute($name, $this->method, $this->pattern);
|
||||
// Setze den Namen auch im routes-Array
|
||||
$this->router->routes[$this->method][$this->pattern]['name'] = $name;
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET-Route registrieren
|
||||
*
|
||||
* @param string $pattern
|
||||
* @param callable $handler
|
||||
*/
|
||||
public function get(string $pattern, callable $handler)
|
||||
public function get(string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
$this->add('GET', $pattern, $handler);
|
||||
return $this->add('GET', $pattern, $handler, $middleware);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST-Route registrieren
|
||||
*
|
||||
* @param string $pattern
|
||||
* @param callable $handler
|
||||
*/
|
||||
public function post(string $pattern, callable $handler)
|
||||
public function post(string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
$this->add('POST', $pattern, $handler);
|
||||
return $this->add('POST', $pattern, $handler, $middleware);
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT-Route registrieren
|
||||
*/
|
||||
public function put(string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
return $this->add('PUT', $pattern, $handler, $middleware);
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH-Route registrieren
|
||||
*/
|
||||
public function patch(string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
return $this->add('PATCH', $pattern, $handler, $middleware);
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE-Route registrieren
|
||||
*/
|
||||
public function delete(string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
return $this->add('DELETE', $pattern, $handler, $middleware);
|
||||
}
|
||||
|
||||
/**
|
||||
* OPTIONS-Route registrieren
|
||||
*/
|
||||
public function options(string $pattern, $handler, array $middleware = [])
|
||||
{
|
||||
return $this->add('OPTIONS', $pattern, $handler, $middleware);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @var callable|null
|
||||
*/
|
||||
private $errorHandler = null;
|
||||
|
||||
/**
|
||||
* Setzt einen globalen Fehler-Handler.
|
||||
* @param callable $handler function(Request $request, \Throwable $e): Response
|
||||
*/
|
||||
public function setErrorHandler(callable $handler): void
|
||||
{
|
||||
$this->errorHandler = $handler;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -59,6 +161,7 @@ class Router
|
|||
*/
|
||||
public function dispatch(Request $request): Response
|
||||
{
|
||||
try {
|
||||
$method = $request->getMethod();
|
||||
$uri = $request->getUri();
|
||||
|
||||
|
|
@ -66,7 +169,7 @@ class Router
|
|||
return new Response('Method Not Allowed', 405);
|
||||
}
|
||||
|
||||
foreach ($this->routes[$method] as $pattern => $handler) {
|
||||
foreach ($this->routes[$method] as $pattern => $route) {
|
||||
$params = [];
|
||||
$regex = $this->convertPatternToRegex($pattern, $params);
|
||||
|
||||
|
|
@ -78,12 +181,232 @@ class Router
|
|||
$params[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$handler = $route['handler'];
|
||||
$routeMiddleware = $route['middleware'] ?? [];
|
||||
|
||||
// Baue die Middleware-Kette auf
|
||||
$middlewareStack = array_merge(
|
||||
$this->globalMiddleware,
|
||||
$routeMiddleware,
|
||||
[
|
||||
function ($request) use ($handler, $params) {
|
||||
// Controller-Support: String "Controller@Methode" oder [ControllerClass, Methode]
|
||||
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 (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);
|
||||
}
|
||||
}
|
||||
return call_user_func($handler, $request, $params);
|
||||
}
|
||||
]
|
||||
);
|
||||
|
||||
// Führe die Middleware-Kette aus
|
||||
$runner = function ($request, $middlewareStack, $index = 0) use (&$runner) {
|
||||
if (!isset($middlewareStack[$index])) {
|
||||
throw new \RuntimeException('Middleware stack exhausted with no response.');
|
||||
}
|
||||
$middleware = $middlewareStack[$index];
|
||||
return $middleware($request, function ($req) use ($runner, $middlewareStack, $index) {
|
||||
return $runner($req, $middlewareStack, $index + 1);
|
||||
});
|
||||
};
|
||||
|
||||
return $runner($request, $middlewareStack);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response('Not Found', 404);
|
||||
} catch (\Throwable $e) {
|
||||
if ($this->errorHandler) {
|
||||
return call_user_func($this->errorHandler, $request, $e);
|
||||
}
|
||||
// Fallback: Standard-Fehlerausgabe
|
||||
return (new Response())->withJson([
|
||||
'error' => 'Internal Server Error',
|
||||
'message' => $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gibt alle registrierten Routen zurück.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRoutes(): array
|
||||
{
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gruppiert Routen unter einem gemeinsamen Prefix und/oder Middleware.
|
||||
*
|
||||
* @param string $prefix
|
||||
* @param callable $callback
|
||||
* @param array $middleware
|
||||
* @return void
|
||||
*/
|
||||
public function group(string $prefix, callable $callback, array $middleware = []): void
|
||||
{
|
||||
$this->groupStack[] = [
|
||||
'prefix' => $prefix,
|
||||
'middleware' => $middleware,
|
||||
];
|
||||
$callback($this);
|
||||
array_pop($this->groupStack);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Route unter einem Namen registrieren (intern genutzt)
|
||||
*/
|
||||
public function nameRoute(string $name, string $method, string $pattern): void
|
||||
{
|
||||
$this->namedRoutes[$name] = [
|
||||
'method' => $method,
|
||||
'pattern' => $pattern,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generiert eine URL anhand des Routennamens und der Parameter
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $params
|
||||
* @return string|null
|
||||
*/
|
||||
public function url(string $name, array $params = []): ?string
|
||||
{
|
||||
if (!isset($this->namedRoutes[$name])) {
|
||||
return null;
|
||||
}
|
||||
$pattern = $this->namedRoutes[$name]['pattern'];
|
||||
// Ersetze Platzhalter im Pattern durch Parameter
|
||||
$url = preg_replace_callback('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', function ($matches) use (&$params) {
|
||||
$key = $matches[1];
|
||||
if (isset($params[$key])) {
|
||||
$value = $params[$key];
|
||||
unset($params[$key]);
|
||||
return $value;
|
||||
}
|
||||
return $matches[0];
|
||||
}, $pattern);
|
||||
// Füge übrige Parameter als Query-String an
|
||||
if (!empty($params)) {
|
||||
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Globale Middleware hinzufügen
|
||||
*
|
||||
* @param callable $middleware
|
||||
* @return void
|
||||
*/
|
||||
public function addMiddleware(callable $middleware): void
|
||||
{
|
||||
$this->globalMiddleware[] = $middleware;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interne Hilfsmethode: Gibt aktuellen Prefix zurück (aus Gruppenstack)
|
||||
*/
|
||||
private function getCurrentPrefix(): string
|
||||
{
|
||||
$prefix = '';
|
||||
foreach ($this->groupStack as $group) {
|
||||
$prefix .= rtrim($group['prefix'], '/');
|
||||
}
|
||||
return $prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interne Hilfsmethode: Gibt alle Middleware aus Gruppenstack zurück
|
||||
*/
|
||||
private function getCurrentGroupMiddleware(): array
|
||||
{
|
||||
$all = [];
|
||||
foreach ($this->groupStack as $group) {
|
||||
foreach ($group['middleware'] as $mw) {
|
||||
$all[] = $mw;
|
||||
}
|
||||
}
|
||||
return $all;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// --- Routen-Caching ---
|
||||
|
||||
/**
|
||||
* Speichert die aktuelle Routenstruktur und benannten Routen als Cache-Datei.
|
||||
*
|
||||
* @param string $file
|
||||
* @return void
|
||||
*/
|
||||
public function cacheRoutes(string $file): void
|
||||
{
|
||||
// Prüfe auf Closures in den Handlern
|
||||
foreach ($this->routes as $method => $routes) {
|
||||
foreach ($routes as $pattern => $route) {
|
||||
if ($route['handler'] instanceof \Closure) {
|
||||
throw new \RuntimeException("Routen-Caching nicht möglich: Handler für $method $pattern ist ein Closure.");
|
||||
}
|
||||
}
|
||||
}
|
||||
$data = [
|
||||
'routes' => $this->routes,
|
||||
'namedRoutes' => $this->namedRoutes,
|
||||
];
|
||||
file_put_contents($file, '<?php return ' . var_export($data, true) . ';');
|
||||
}
|
||||
|
||||
/**
|
||||
* Lädt die Routenstruktur und benannten Routen aus einer Cache-Datei.
|
||||
*
|
||||
* @param string $file
|
||||
* @return void
|
||||
*/
|
||||
public function loadCachedRoutes(string $file): void
|
||||
{
|
||||
if (!file_exists($file)) {
|
||||
throw new \RuntimeException("Routen-Cache-Datei nicht gefunden: $file");
|
||||
}
|
||||
$data = include $file;
|
||||
if (!is_array($data) || !isset($data['routes'], $data['namedRoutes'])) {
|
||||
throw new \RuntimeException("Ungültiges Routen-Cache-Format in: $file");
|
||||
}
|
||||
// Prüfe auf Closures im Cache (kann durch vorherigen Fehler entstanden sein)
|
||||
foreach ($data['routes'] as $method => $routes) {
|
||||
foreach ($routes as $pattern => $route) {
|
||||
if (isset($route['handler']) && $route['handler'] instanceof \Closure) {
|
||||
// Lösche fehlerhaften Cache und lade nicht
|
||||
@unlink($file);
|
||||
// Optional: Log oder Hinweis
|
||||
trigger_error("Fehlerhafter Routen-Cache (enthält Closures) wurde gelöscht: $file", E_USER_WARNING);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->routes = $data['routes'];
|
||||
$this->namedRoutes = $data['namedRoutes'];
|
||||
$this->routesAreCached = true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Wandelt ein Routen-Pattern in einen Regex um und extrahiert Parameternamen
|
||||
|
|
@ -96,11 +419,13 @@ class Router
|
|||
*/
|
||||
private function convertPatternToRegex(string $pattern, array &$params): string
|
||||
{
|
||||
// Erlaube Constraints: {param:regex}
|
||||
$regex = preg_replace_callback(
|
||||
'#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#',
|
||||
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(:([^}]+))?\}#',
|
||||
function ($matches) use (&$params) {
|
||||
$params[] = $matches[1];
|
||||
return '(?P<' . $matches[1] . '>[^/]+)';
|
||||
$constraint = isset($matches[3]) ? $matches[3] : '[^/]+';
|
||||
return '(?P<' . $matches[1] . '>' . $constraint . ')';
|
||||
},
|
||||
$pattern
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue