Refactoring, README-Optimierung, Middleware-Beispiele ergänzt, Codeblöcke korrigiert und Doku aktualisiert
This commit is contained in:
parent
e4d2b5d874
commit
d903d47759
11 changed files with 428 additions and 181 deletions
54
CHANGELOG.md
Normal file
54
CHANGELOG.md
Normal file
|
|
@ -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.
|
||||||
|
|
||||||
|
---
|
||||||
142
README.md
142
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
|
- **Optionales Routen-Caching:** Cachebare Routen als JSON speichern, CLI-Tool zur Verwaltung
|
||||||
- **CLI-Tool:** Cache löschen, neu bauen, Routen auflisten
|
- **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
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$router->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
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Middleware für Gruppen
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
## Schnellstart
|
## Schnellstart
|
||||||
|
|
||||||
### 1. Installation
|
### 1. Installation
|
||||||
|
|
@ -58,20 +114,44 @@ $router->get('/user/{id}', function (Request $request, array $params) use ($rout
|
||||||
'profile_url' => $profileUrl
|
'profile_url' => $profileUrl
|
||||||
]);
|
]);
|
||||||
})->name('user.profile');
|
})->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
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$router->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
|
## 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']);
|
$url = $router->url('article.show', ['slug' => 'mein-artikel']);
|
||||||
// Ergebnis: /article/mein-artikel
|
// Ergebnis: /article/mein-artikel
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Route-Gruppen & Prefixes
|
## Route-Gruppen & Prefixes
|
||||||
|
|
@ -101,16 +180,19 @@ $router->group('/api', function ($router) {
|
||||||
$router->post('/users', [UserController::class, 'create']);
|
$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
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
// In example/routes/web.php
|
// In example/routes/web.php
|
||||||
|
|
||||||
// Leitet intern auf die named route 'user.profile' weiter, id=99, foo=bar
|
// Leitet intern auf die named route 'user.profile' weiter, id=99, foo=bar
|
||||||
|
|
@ -124,6 +206,7 @@ Das Ergebnis ist identisch zu einem Aufruf von `/user/99?foo=bar`, aber ohne das
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Response-Methoden
|
## Response-Methoden
|
||||||
|
|
||||||
Die Response-Klasse bietet folgende Methoden:
|
Die Response-Klasse bietet folgende Methoden:
|
||||||
|
|
@ -146,6 +229,8 @@ Die Response-Klasse bietet folgende Methoden:
|
||||||
### Beispiele
|
### Beispiele
|
||||||
|
|
||||||
```php
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
// JSON-Antwort
|
// JSON-Antwort
|
||||||
return (new Response())->withJson(['success' => true]);
|
return (new Response())->withJson(['success' => true]);
|
||||||
// HTML-Antwort
|
// 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
|
## Routen-Dokumentation
|
||||||
|
|
||||||
- **Alle Routen als JSON:** `/routes`
|
- **Alle Routen als JSON:** `/routes`
|
||||||
|
|
@ -226,22 +318,13 @@ function (Request $request, array $params)
|
||||||
|
|
||||||
## Routen-Caching & CLI
|
## Routen-Caching & CLI
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
- **Cache neu bauen:**
|
- **Cache neu bauen:**
|
||||||
|
|
||||||
`bin/route-cache build`
|
`bin/route-cache build`
|
||||||
|
|
||||||
- **Cache löschen:**
|
- **Cache löschen:**
|
||||||
|
|
||||||
`bin/route-cache clear`
|
`bin/route-cache clear`
|
||||||
|
|
||||||
- **Cache anzeigen:**
|
- **Cache anzeigen:**
|
||||||
|
|
||||||
`bin/route-cache show`
|
`bin/route-cache show`
|
||||||
|
|
||||||
- **Alle Routen auflisten:**
|
- **Alle Routen auflisten:**
|
||||||
|
|
||||||
`bin/route-cache list`
|
`bin/route-cache list`
|
||||||
|
|
||||||
### CLI-Tool verwenden
|
### CLI-Tool verwenden
|
||||||
|
|
@ -260,7 +343,6 @@ Verfügbare Befehle:
|
||||||
- `show` – Cache anzeigen (JSON)
|
- `show` – Cache anzeigen (JSON)
|
||||||
- `list` – Alle registrierten Routen anzeigen
|
- `list` – Alle registrierten Routen anzeigen
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Projektstruktur
|
## Projektstruktur
|
||||||
|
|
@ -271,8 +353,6 @@ example/ # Demo-Anwendung (Controller, Routen, Public)
|
||||||
bin/ # CLI-Tools
|
bin/ # CLI-Tools
|
||||||
cache/ # Routen-Cache (JSON)
|
cache/ # Routen-Cache (JSON)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -344,13 +424,9 @@ $controller = $container->get(UserController::class);
|
||||||
## Weiterführendes
|
## Weiterführendes
|
||||||
|
|
||||||
- **Eigene Controller:** Lege sie unter `example/app/Controller` ab und verwende sie als Handler.
|
- **Eigene Controller:** Lege sie unter `example/app/Controller` ab und verwende sie als Handler.
|
||||||
|
|
||||||
- **Middleware:** Schreibe eigene Middleware als Closure oder Klasse.
|
- **Middleware:** Schreibe eigene Middleware als Closure oder Klasse.
|
||||||
|
|
||||||
- **Tests & Erweiterungen:** Das Framework ist modular und kann leicht erweitert werden.
|
- **Tests & Erweiterungen:** Das Framework ist modular und kann leicht erweitert werden.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
#!/usr/bin/env php
|
#!/usr/bin/env php
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
// CLI-Tool zur Verwaltung des Routen-Caches für MariaCore Router
|
// ===========================================
|
||||||
// Usage:
|
// MariaCore Router: Route-Cache CLI-Tool
|
||||||
|
// ===========================================
|
||||||
|
// Befehle:
|
||||||
// bin/route-cache clear - Cache löschen
|
// bin/route-cache clear - Cache löschen
|
||||||
// bin/route-cache build - Cache neu generieren (aus routes/web.php)
|
// bin/route-cache build - Cache neu generieren (aus routes/web.php)
|
||||||
// bin/route-cache show - Cache anzeigen (JSON)
|
// bin/route-cache show - Cache anzeigen (JSON)
|
||||||
// bin/route-cache list - Alle Routen ausgeben (aus web.php)
|
// bin/route-cache list - Alle registrierten Routen anzeigen
|
||||||
|
|
||||||
require_once __DIR__ . '/../vendor/autoload.php';
|
require_once __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
|
|
@ -19,11 +21,11 @@ $routeCache = new RouteCache($cacheFile);
|
||||||
function printUsage()
|
function printUsage()
|
||||||
{
|
{
|
||||||
echo "MariaCore Route Cache CLI\n";
|
echo "MariaCore Route Cache CLI\n";
|
||||||
echo "Usage:\n";
|
echo "Befehle:\n";
|
||||||
echo " route-cache clear - Cache löschen\n";
|
echo " route-cache clear - Cache löschen\n";
|
||||||
echo " route-cache build - Cache neu generieren (aus routes/web.php)\n";
|
echo " route-cache build - Cache neu generieren (aus routes/web.php)\n";
|
||||||
echo " route-cache show - Cache anzeigen (JSON)\n";
|
echo " route-cache show - Cache anzeigen (JSON)\n";
|
||||||
echo " route-cache list - Alle Routen ausgeben (aus web.php)\n";
|
echo " route-cache list - Alle registrierten Routen anzeigen\n";
|
||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -31,51 +33,71 @@ $cmd = $argv[1] ?? null;
|
||||||
|
|
||||||
switch ($cmd) {
|
switch ($cmd) {
|
||||||
case 'clear':
|
case 'clear':
|
||||||
$routeCache->clear();
|
try {
|
||||||
echo "Route-Cache wurde gelöscht: $cacheFile\n";
|
$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;
|
break;
|
||||||
|
|
||||||
case 'build':
|
case 'build':
|
||||||
$router = new Router();
|
try {
|
||||||
require __DIR__ . '/../example/routes/web.php';
|
$router = new Router();
|
||||||
$routeCache->write($router->routes);
|
require __DIR__ . '/../example/routes/web.php';
|
||||||
echo "Route-Cache wurde neu generiert: $cacheFile\n";
|
$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;
|
break;
|
||||||
|
|
||||||
case 'show':
|
case 'show':
|
||||||
$data = $routeCache->read();
|
try {
|
||||||
if ($data === null) {
|
$data = $routeCache->read();
|
||||||
echo "Kein Route-Cache gefunden: $cacheFile\n";
|
if ($data === null) {
|
||||||
exit(1);
|
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;
|
break;
|
||||||
|
|
||||||
case 'list':
|
case 'list':
|
||||||
$router = new Router();
|
try {
|
||||||
require __DIR__ . '/../example/routes/web.php';
|
$router = new Router();
|
||||||
echo "Alle registrierten Routen:\n";
|
require __DIR__ . '/../example/routes/web.php';
|
||||||
echo str_pad("METHODE", 8) . str_pad("PFAD", 30) . str_pad("NAME", 25) . "HANDLER\n";
|
echo "Alle registrierten Routen:\n";
|
||||||
echo str_repeat("-", 80) . "\n";
|
echo str_pad("METHODE", 8) . str_pad("PFAD", 30) . str_pad("NAME", 25) . "HANDLER\n";
|
||||||
foreach ($router->routes as $method => $routesArr) {
|
echo str_repeat("-", 80) . "\n";
|
||||||
foreach ($routesArr as $pattern => $info) {
|
foreach ($router->routes as $method => $routesArr) {
|
||||||
$name = $info['name'] ?? '';
|
foreach ($routesArr as $pattern => $info) {
|
||||||
$handler = $info['handler'];
|
$name = $info['name'] ?? '';
|
||||||
if (is_string($handler)) {
|
$handler = $info['handler'];
|
||||||
$handlerStr = $handler;
|
if (is_string($handler)) {
|
||||||
} elseif (is_array($handler)) {
|
$handlerStr = $handler;
|
||||||
if (isset($handler[0]) && isset($handler[1])) {
|
} elseif (is_array($handler)) {
|
||||||
$handlerStr = (is_string($handler[0]) ? $handler[0] : get_class($handler[0])) . '::' . $handler[1];
|
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 {
|
} else {
|
||||||
$handlerStr = '[Array]';
|
$handlerStr = gettype($handler);
|
||||||
}
|
}
|
||||||
} elseif ($handler instanceof Closure) {
|
echo str_pad($method, 8) . str_pad($pattern, 30) . str_pad($name, 25) . $handlerStr . "\n";
|
||||||
$handlerStr = 'Closure';
|
|
||||||
} else {
|
|
||||||
$handlerStr = gettype($handler);
|
|
||||||
}
|
}
|
||||||
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;
|
break;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,10 +5,21 @@ namespace App\Controller;
|
||||||
use MyCodebox\MariaCore\Http\Request;
|
use MyCodebox\MariaCore\Http\Request;
|
||||||
use MyCodebox\MariaCore\Http\Response;
|
use MyCodebox\MariaCore\Http\Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Beispiel-Controller für Begrüßungen.
|
||||||
|
*/
|
||||||
class HelloController
|
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');
|
$name = htmlspecialchars($params['name'] ?? 'Gast');
|
||||||
return (new Response())->withHtml("<h1>Hallo aus dem Controller, {$name}!</h1>");
|
return (new Response())->withHtml("<h1>Hallo aus dem Controller, {$name}!</h1>");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,16 +5,34 @@ namespace App\Controller;
|
||||||
use MyCodebox\MariaCore\Http\Request;
|
use MyCodebox\MariaCore\Http\Request;
|
||||||
use MyCodebox\MariaCore\Http\Response;
|
use MyCodebox\MariaCore\Http\Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Controller für die Anzeige und Ausgabe der registrierten Routen.
|
||||||
|
*/
|
||||||
class RoutesController
|
class RoutesController
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @var mixed Router-Instanz (typischerweise MyCodebox\MariaCore\Router)
|
||||||
|
*/
|
||||||
protected $router;
|
protected $router;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Konstruktor.
|
||||||
|
*
|
||||||
|
* @param mixed $router
|
||||||
|
*/
|
||||||
public function __construct($router)
|
public function __construct($router)
|
||||||
{
|
{
|
||||||
$this->router = $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 = [];
|
$routes = [];
|
||||||
foreach ($this->router->getRoutes() as $method => $paths) {
|
foreach ($this->router->getRoutes() as $method => $paths) {
|
||||||
|
|
@ -30,7 +48,14 @@ class RoutesController
|
||||||
return (new Response())->withJson($routes, 200, JSON_PRETTY_PRINT);
|
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 = [];
|
$routes = [];
|
||||||
foreach ($this->router->getRoutes() as $method => $paths) {
|
foreach ($this->router->getRoutes() as $method => $paths) {
|
||||||
|
|
@ -45,8 +70,8 @@ class RoutesController
|
||||||
}
|
}
|
||||||
$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>';
|
$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) {
|
foreach ($routes as $route) {
|
||||||
$link = '<a href="' . htmlspecialchars($route['path']) . '">' . htmlspecialchars($route['path']) . '</a>';
|
$link = '<a href="' . htmlspecialchars($route['path'], ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($route['path'], ENT_QUOTES, 'UTF-8') . '</a>';
|
||||||
$html .= '<tr><td>' . htmlspecialchars($route['method']) . '</td><td>' . $link . '</td><td>' . htmlspecialchars($route['name']) . '</td><td>' . $route['middleware_count'] . '</td></tr>';
|
$html .= '<tr><td>' . htmlspecialchars($route['method'], ENT_QUOTES, 'UTF-8') . '</td><td>' . $link . '</td><td>' . htmlspecialchars($route['name'], ENT_QUOTES, 'UTF-8') . '</td><td>' . (int)$route['middleware_count'] . '</td></tr>';
|
||||||
}
|
}
|
||||||
$html .= '</table>';
|
$html .= '</table>';
|
||||||
return (new Response())->withHtml($html);
|
return (new Response())->withHtml($html);
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
// Composer Autoloader
|
// ===========================================
|
||||||
|
// Bootstrap & Router-Setup für Demo-Anwendung
|
||||||
|
// ===========================================
|
||||||
|
|
||||||
|
// Composer Autoloader laden
|
||||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
require_once __DIR__ . '/../../vendor/autoload.php';
|
||||||
|
|
||||||
use MyCodebox\MariaCore\Http\Request;
|
use MyCodebox\MariaCore\Http\Request;
|
||||||
|
|
@ -11,17 +15,16 @@ use MyCodebox\MariaCore\Cache\RouteCache;
|
||||||
// Router-Instanz erstellen
|
// Router-Instanz erstellen
|
||||||
$router = new Router();
|
$router = new Router();
|
||||||
|
|
||||||
// Beispiel: Globale Middleware (wird bei jedem Request ausgeführt)
|
// Globale Middleware (wird bei jedem Request ausgeführt)
|
||||||
$router->addMiddleware(function (Request $request, callable $next) {
|
$router->addMiddleware(function (Request $request, callable $next) {
|
||||||
// Beispiel: Logging
|
// Logging-Beispiel
|
||||||
error_log('Request: ' . $request->getMethod() . ' ' . $request->getUri());
|
error_log('[Router] ' . $request->getMethod() . ' ' . $request->getUri());
|
||||||
// Weiter zur nächsten Middleware/Handler
|
// Weiter zur nächsten Middleware/Handler
|
||||||
return $next($request);
|
return $next($request);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Beispiel: Custom Error Handler
|
// Custom Error Handler (gibt Fehler als JSON zurück)
|
||||||
$router->setErrorHandler(function (Request $request, Throwable $e) {
|
$router->setErrorHandler(function (Request $request, Throwable $e) {
|
||||||
// Beispiel: Gib Fehler als JSON zurück, mit Status 500
|
|
||||||
return (new Response())->withJson([
|
return (new Response())->withJson([
|
||||||
'error' => 'Fehler im Router',
|
'error' => 'Fehler im Router',
|
||||||
'message' => $e->getMessage(),
|
'message' => $e->getMessage(),
|
||||||
|
|
@ -29,7 +32,9 @@ $router->setErrorHandler(function (Request $request, Throwable $e) {
|
||||||
], 500);
|
], 500);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Immer web.php laden (alle Routen, inkl. Closures)
|
// -------------------------------------------------
|
||||||
|
// Routen registrieren (immer web.php laden)
|
||||||
|
// -------------------------------------------------
|
||||||
require __DIR__ . '/../routes/web.php';
|
require __DIR__ . '/../routes/web.php';
|
||||||
|
|
||||||
// Nach dem Registrieren aller Routen: cachebare Infos extrahieren und speichern
|
// Nach dem Registrieren aller Routen: cachebare Infos extrahieren und speichern
|
||||||
|
|
|
||||||
|
|
@ -6,22 +6,21 @@ use MyCodebox\MariaCore\Http\Response;
|
||||||
use App\Controller\HelloController;
|
use App\Controller\HelloController;
|
||||||
use App\Controller\RoutesController;
|
use App\Controller\RoutesController;
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// Controller-Instanzen erzeugen
|
// Controller-Instanzen erzeugen
|
||||||
|
// ---------------------------------------------------
|
||||||
$routesController = new RoutesController($router);
|
$routesController = new RoutesController($router);
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// GET-Routen
|
// GET-Routen
|
||||||
|
// ---------------------------------------------------
|
||||||
$router->get('/', function (Request $request, array $params) {
|
$router->get('/', function (Request $request, array $params) {
|
||||||
return (new Response())->withHtml('<h1>Willkommen auf der Startseite!</h1>');
|
return (new Response())->withHtml('<h1>Willkommen auf der Startseite!</h1>');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
$router->get('/routes', [$routesController, 'json']);
|
$router->get('/routes', [$routesController, 'json']);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
$router->get('/routes.html', [$routesController, 'html']);
|
$router->get('/routes.html', [$routesController, 'html']);
|
||||||
|
|
||||||
|
|
||||||
$router->get('/protected', function (Request $request, array $params) {
|
$router->get('/protected', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['message' => 'Du bist authentifiziert!']);
|
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');
|
})->name('user.profile');
|
||||||
|
|
||||||
|
|
||||||
$router->get('/go-home', function (Request $request, array $params) {
|
$router->get('/go-home', function (Request $request, array $params) {
|
||||||
|
|
||||||
return (new Response())->withRedirect('/');
|
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']);
|
return $router->forward('user.profile', ['id' => 99], ['foo' => 'bar']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
$router->get('/plain', function (Request $request, array $params) {
|
$router->get('/plain', function (Request $request, array $params) {
|
||||||
return (new Response())->withText("Dies ist eine reine Textantwort.");
|
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');
|
return (new Response())->withDownload('beispiel.txt', $content, 'text/plain');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// POST-Routen
|
// POST-Routen
|
||||||
|
// ---------------------------------------------------
|
||||||
$router->post('/users', function (Request $request, array $params) {
|
$router->post('/users', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['message' => 'User created'], 201);
|
return (new Response())->withJson(['message' => 'User created'], 201);
|
||||||
});
|
});
|
||||||
|
|
@ -77,27 +75,39 @@ $router->post('/submit', function (Request $request, array $params) {
|
||||||
return (new Response())->withHtml("<h1>Formular empfangen, Name: {$name}</h1>");
|
return (new Response())->withHtml("<h1>Formular empfangen, Name: {$name}</h1>");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// PUT-Routen
|
// PUT-Routen
|
||||||
|
// ---------------------------------------------------
|
||||||
$router->put('/users/{id}', function (Request $request, array $params) {
|
$router->put('/users/{id}', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]);
|
return (new Response())->withJson(['message' => 'User updated', 'id' => $params['id'] ?? null]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// PATCH-Routen
|
// PATCH-Routen
|
||||||
|
// ---------------------------------------------------
|
||||||
$router->patch('/users/{id}', function (Request $request, array $params) {
|
$router->patch('/users/{id}', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]);
|
return (new Response())->withJson(['message' => 'User partially updated', 'id' => $params['id'] ?? null]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// DELETE-Routen
|
// DELETE-Routen
|
||||||
|
// ---------------------------------------------------
|
||||||
$router->delete('/users/{id}', function (Request $request, array $params) {
|
$router->delete('/users/{id}', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]);
|
return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------
|
||||||
// OPTIONS-Routen
|
// OPTIONS-Routen
|
||||||
|
// ---------------------------------------------------
|
||||||
$router->options('/users', function (Request $request, array $params) {
|
$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->group('/api', function ($router) {
|
||||||
$router->get('/users', function (Request $request, array $params) {
|
$router->get('/users', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['users' => ['Alice', 'Bob', 'Charlie']]);
|
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]);
|
return (new Response())->withJson(['message' => 'User deleted', 'id' => $params['id'] ?? null]);
|
||||||
});
|
});
|
||||||
$router->options('/users', function (Request $request, array $params) {
|
$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) {
|
$router->patch('/users', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson([
|
return (new Response())->withJson([
|
||||||
'message' => 'Alle User wurden (demo) teilweise aktualisiert.'
|
'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) {
|
$router->get('/users/{id}', function (Request $request, array $params) use ($router) {
|
||||||
$id = $params['id'] ?? null;
|
$id = $params['id'] ?? null;
|
||||||
$profileUrl = $router->url('user.profile', ['id' => $id]);
|
$profileUrl = $router->url('user.profile', ['id' => $id]);
|
||||||
|
|
@ -132,7 +144,7 @@ $router->group('/api', function ($router) {
|
||||||
'profile_url' => $profileUrl
|
'profile_url' => $profileUrl
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
// Ergänzung: OPTIONS /api/users/{id}
|
// OPTIONS /api/users/{id}
|
||||||
$router->options('/users/{id}', function (Request $request, array $params) {
|
$router->options('/users/{id}', function (Request $request, array $params) {
|
||||||
return (new Response())
|
return (new Response())
|
||||||
->withHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')
|
->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->group('/admin', function ($router) {
|
||||||
$router->get('/dashboard', function (Request $request, array $params) {
|
$router->get('/dashboard', function (Request $request, array $params) {
|
||||||
return (new Response())->withJson(['dashboard' => 'Admin stats here']);
|
return (new Response())->withJson(['dashboard' => 'Admin stats here']);
|
||||||
|
|
|
||||||
|
|
@ -3,13 +3,16 @@
|
||||||
namespace MyCodebox\MariaCore\Cache;
|
namespace MyCodebox\MariaCore\Cache;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* RouteCache
|
* Class RouteCache
|
||||||
*
|
*
|
||||||
* Verwaltet das Caching der Routen-Metadaten als JSON-Datei.
|
* Verwaltet das Caching der Routen-Metadaten als JSON-Datei.
|
||||||
* Cacht nur serialisierbare Handler (Strings, Controller-Arrays), keine Closures!
|
* Cacht nur serialisierbare Handler (Strings, Controller-Arrays), keine Closures!
|
||||||
*/
|
*/
|
||||||
class RouteCache
|
class RouteCache
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @var string Pfad zur Cache-Datei
|
||||||
|
*/
|
||||||
private string $cacheFile;
|
private string $cacheFile;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -52,12 +55,17 @@ class RouteCache
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!is_dir(dirname($this->cacheFile))) {
|
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)) {
|
if (!file_exists($this->cacheFile)) {
|
||||||
return null;
|
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
|
public function clear(): void
|
||||||
{
|
{
|
||||||
if (file_exists($this->cacheFile)) {
|
if (file_exists($this->cacheFile)) {
|
||||||
unlink($this->cacheFile);
|
if (!@unlink($this->cacheFile)) {
|
||||||
|
throw new \RuntimeException('Cache-Datei konnte nicht gelöscht werden: ' . $this->cacheFile);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,12 @@ namespace MyCodebox\MariaCore\Http;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simplified PSR-7-inspired Request class.
|
* Simplified PSR-7-inspired Request class.
|
||||||
|
*
|
||||||
|
* @property string $method
|
||||||
|
* @property string $uri
|
||||||
|
* @property array $queryParams
|
||||||
|
* @property array $parsedBody
|
||||||
|
* @property array $headers
|
||||||
*/
|
*/
|
||||||
class Request
|
class Request
|
||||||
{
|
{
|
||||||
|
|
@ -13,6 +19,11 @@ class Request
|
||||||
protected array $parsedBody;
|
protected array $parsedBody;
|
||||||
protected array $headers;
|
protected array $headers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request constructor.
|
||||||
|
*
|
||||||
|
* Initializes the request object from PHP globals.
|
||||||
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
$this->method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
||||||
|
|
@ -24,6 +35,8 @@ class Request
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the HTTP method.
|
* Get the HTTP method.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function getMethod(): string
|
public function getMethod(): string
|
||||||
{
|
{
|
||||||
|
|
@ -32,6 +45,8 @@ class Request
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the URI path.
|
* Get the URI path.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
*/
|
*/
|
||||||
public function getUri(): string
|
public function getUri(): string
|
||||||
{
|
{
|
||||||
|
|
@ -40,6 +55,8 @@ class Request
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get query parameters.
|
* Get query parameters.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function getQueryParams(): array
|
public function getQueryParams(): array
|
||||||
{
|
{
|
||||||
|
|
@ -48,6 +65,8 @@ class Request
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get parsed body parameters (POST data).
|
* Get parsed body parameters (POST data).
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function getParsedBody(): array
|
public function getParsedBody(): array
|
||||||
{
|
{
|
||||||
|
|
@ -56,6 +75,9 @@ class Request
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all HTTP headers as an associative array.
|
* Get all HTTP headers as an associative array.
|
||||||
|
* Header-Namen sind immer klein geschrieben.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function getHeaders(): array
|
public function getHeaders(): array
|
||||||
{
|
{
|
||||||
|
|
@ -64,20 +86,19 @@ class Request
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a specific header value or null if not found.
|
* 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
|
public function getHeader(string $name): ?string
|
||||||
{
|
{
|
||||||
$name = strtolower($name);
|
$name = strtolower($name);
|
||||||
foreach ($this->headers as $key => $value) {
|
return $this->headers[$name] ?? null;
|
||||||
if (strtolower($key) === $name) {
|
|
||||||
return $value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 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' => ...]
|
* @param array $override ['method' => ..., 'uri' => ..., 'queryParams' => ..., 'parsedBody' => ..., 'headers' => ...]
|
||||||
* @return static
|
* @return static
|
||||||
|
|
@ -98,26 +119,28 @@ class Request
|
||||||
$instance->parsedBody = $override['parsedBody'];
|
$instance->parsedBody = $override['parsedBody'];
|
||||||
}
|
}
|
||||||
if (isset($override['headers'])) {
|
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;
|
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.
|
* Parse all HTTP headers from $_SERVER.
|
||||||
|
* Header-Namen werden als Kleinbuchstaben gespeichert.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
*/
|
*/
|
||||||
protected function parseHeaders(): array
|
protected function parseHeaders(): array
|
||||||
{
|
{
|
||||||
$headers = [];
|
$headers = [];
|
||||||
foreach ($_SERVER as $key => $value) {
|
foreach ($_SERVER as $key => $value) {
|
||||||
if (str_starts_with($key, 'HTTP_')) {
|
if (str_starts_with($key, 'HTTP_')) {
|
||||||
$header = str_replace('_', '-', strtolower(substr($key, 5)));
|
$header = strtolower(str_replace('_', '-', substr($key, 5)));
|
||||||
$headers[$header] = $value;
|
$headers[$header] = $value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -179,14 +179,21 @@ class Response
|
||||||
/**
|
/**
|
||||||
* Return a new response with JSON body and appropriate content type.
|
* Return a new response with JSON body and appropriate content type.
|
||||||
*
|
*
|
||||||
* @param mixed $data
|
* @param mixed $data Data to encode as JSON
|
||||||
* @param int $statusCode
|
* @param int $statusCode HTTP status code
|
||||||
* @param int $jsonOptions
|
* @param int $jsonOptions JSON encoding options
|
||||||
* @return self
|
* @return self
|
||||||
*/
|
*/
|
||||||
public function withJson(mixed $data, int $statusCode = 200, int $jsonOptions = 0): self
|
public function withJson(mixed $data, int $statusCode = 200, int $jsonOptions = 0): self
|
||||||
{
|
{
|
||||||
$body = json_encode($data, $jsonOptions | JSON_UNESCAPED_UNICODE);
|
$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 = clone $this;
|
||||||
$clone->body = $body;
|
$clone->body = $body;
|
||||||
$clone->statusCode = $statusCode;
|
$clone->statusCode = $statusCode;
|
||||||
|
|
|
||||||
111
src/Router.php
111
src/Router.php
|
|
@ -8,12 +8,12 @@ use MyCodebox\MariaCore\Http\Response;
|
||||||
/**
|
/**
|
||||||
* Class Router
|
* 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
|
class Router
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* All registered routes, grouped by HTTP method.
|
* Registrierte Routen, gruppiert nach HTTP-Methode.
|
||||||
* @var array<string, array>
|
* @var array<string, array>
|
||||||
*/
|
*/
|
||||||
public array $routes = [
|
public array $routes = [
|
||||||
|
|
@ -23,35 +23,35 @@ class Router
|
||||||
'PATCH' => [],
|
'PATCH' => [],
|
||||||
'DELETE' => [],
|
'DELETE' => [],
|
||||||
'OPTIONS' => [],
|
'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<string, array{method: string, pattern: string}>
|
* @var array<string, array{method: string, pattern: string}>
|
||||||
*/
|
*/
|
||||||
public array $namedRoutes = [];
|
public array $namedRoutes = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stack for route groups (prefixes and middleware).
|
* Stack für Route-Gruppen (Prefix & Middleware).
|
||||||
* @var array<int, array{prefix: string, middleware: array}>
|
* @var array<int, array{prefix: string, middleware: array}>
|
||||||
*/
|
*/
|
||||||
private array $groupStack = [];
|
private array $groupStack = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Global middleware applied to every route.
|
* Globale Middleware, die auf jede Route angewendet wird.
|
||||||
* @var callable[]
|
* @var callable[]
|
||||||
*/
|
*/
|
||||||
private array $globalMiddleware = [];
|
private array $globalMiddleware = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register a route with optional middleware.
|
* Registriert eine Route mit optionaler Middleware.
|
||||||
*
|
*
|
||||||
* @param string $method
|
* @param string $method
|
||||||
* @param string $pattern
|
* @param string $pattern
|
||||||
* @param callable|string|array $handler
|
* @param callable|string|array $handler
|
||||||
* @param array $middleware
|
* @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 = [])
|
public function add(string $method, string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
|
|
@ -72,7 +72,7 @@ class Router
|
||||||
'name' => null,
|
'name' => null,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Return a RouteRegistrar object for method chaining (e.g. ->name())
|
// RouteRegistrar für ->name()
|
||||||
return new class($this, $method, $pattern) {
|
return new class($this, $method, $pattern) {
|
||||||
private $router;
|
private $router;
|
||||||
private $method;
|
private $method;
|
||||||
|
|
@ -92,61 +92,47 @@ class Router
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** GET-Route registrieren. */
|
||||||
* Register a GET route.
|
|
||||||
*/
|
|
||||||
public function get(string $pattern, callable|string|array $handler, array $middleware = [])
|
public function get(string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
return $this->add('GET', $pattern, $handler, $middleware);
|
return $this->add('GET', $pattern, $handler, $middleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** POST-Route registrieren. */
|
||||||
* Register a POST route.
|
|
||||||
*/
|
|
||||||
public function post(string $pattern, callable|string|array $handler, array $middleware = [])
|
public function post(string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
return $this->add('POST', $pattern, $handler, $middleware);
|
return $this->add('POST', $pattern, $handler, $middleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** PUT-Route registrieren. */
|
||||||
* Register a PUT route.
|
|
||||||
*/
|
|
||||||
public function put(string $pattern, callable|string|array $handler, array $middleware = [])
|
public function put(string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
return $this->add('PUT', $pattern, $handler, $middleware);
|
return $this->add('PUT', $pattern, $handler, $middleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** PATCH-Route registrieren. */
|
||||||
* Register a PATCH route.
|
|
||||||
*/
|
|
||||||
public function patch(string $pattern, callable|string|array $handler, array $middleware = [])
|
public function patch(string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
return $this->add('PATCH', $pattern, $handler, $middleware);
|
return $this->add('PATCH', $pattern, $handler, $middleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** DELETE-Route registrieren. */
|
||||||
* Register a DELETE route.
|
|
||||||
*/
|
|
||||||
public function delete(string $pattern, callable|string|array $handler, array $middleware = [])
|
public function delete(string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
return $this->add('DELETE', $pattern, $handler, $middleware);
|
return $this->add('DELETE', $pattern, $handler, $middleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** OPTIONS-Route registrieren. */
|
||||||
* Register an OPTIONS route.
|
|
||||||
*/
|
|
||||||
public function options(string $pattern, callable|string|array $handler, array $middleware = [])
|
public function options(string $pattern, callable|string|array $handler, array $middleware = [])
|
||||||
{
|
{
|
||||||
return $this->add('OPTIONS', $pattern, $handler, $middleware);
|
return $this->add('OPTIONS', $pattern, $handler, $middleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @var callable|null */
|
||||||
* @var callable|null
|
|
||||||
*/
|
|
||||||
private $errorHandler = null;
|
private $errorHandler = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set a global error handler.
|
* Setzt einen globalen Error-Handler.
|
||||||
* @param callable $handler function(Request $request, \Throwable $e): Response
|
* @param callable $handler function(Request $request, \Throwable $e): Response
|
||||||
*/
|
*/
|
||||||
public function setErrorHandler(callable $handler): void
|
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
|
* @param Request $request
|
||||||
* @return Response
|
* @return Response
|
||||||
|
|
@ -175,7 +161,7 @@ class Router
|
||||||
$regex = $this->convertPatternToRegex($pattern, $params);
|
$regex = $this->convertPatternToRegex($pattern, $params);
|
||||||
|
|
||||||
if (preg_match($regex, $uri, $matches)) {
|
if (preg_match($regex, $uri, $matches)) {
|
||||||
// Extract parameters
|
// Parameter extrahieren
|
||||||
$params = [];
|
$params = [];
|
||||||
foreach ($matches as $key => $value) {
|
foreach ($matches as $key => $value) {
|
||||||
if (!is_int($key)) {
|
if (!is_int($key)) {
|
||||||
|
|
@ -186,36 +172,47 @@ class Router
|
||||||
$handler = $route['handler'];
|
$handler = $route['handler'];
|
||||||
$routeMiddleware = $route['middleware'] ?? [];
|
$routeMiddleware = $route['middleware'] ?? [];
|
||||||
|
|
||||||
// Build middleware stack
|
// Middleware-Stack bauen
|
||||||
$middlewareStack = array_merge(
|
$middlewareStack = array_merge(
|
||||||
$this->globalMiddleware,
|
$this->globalMiddleware,
|
||||||
$routeMiddleware,
|
$routeMiddleware,
|
||||||
[
|
[
|
||||||
function ($request) use ($handler, $params) {
|
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) {
|
if (is_string($handler) && strpos($handler, '@') !== false) {
|
||||||
[$class, $method] = explode('@', $handler, 2);
|
[$class, $method] = explode('@', $handler, 2);
|
||||||
if (class_exists($class)) {
|
if (class_exists($class)) {
|
||||||
$controller = new $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 (is_array($handler) && count($handler) === 2 && is_string($handler[0])) {
|
||||||
if (class_exists($handler[0])) {
|
if (class_exists($handler[0])) {
|
||||||
$controller = new $handler[0]();
|
$controller = new $handler[0]();
|
||||||
$method = $handler[1];
|
$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) {
|
$runner = function ($request, $middlewareStack, $index = 0) use (&$runner) {
|
||||||
if (!isset($middlewareStack[$index])) {
|
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];
|
$middleware = $middlewareStack[$index];
|
||||||
return $middleware($request, function ($req) use ($runner, $middlewareStack, $index) {
|
return $middleware($request, function ($req) use ($runner, $middlewareStack, $index) {
|
||||||
|
|
@ -232,7 +229,7 @@ class Router
|
||||||
if ($this->errorHandler) {
|
if ($this->errorHandler) {
|
||||||
return call_user_func($this->errorHandler, $request, $e);
|
return call_user_func($this->errorHandler, $request, $e);
|
||||||
}
|
}
|
||||||
// Fallback: Standard error output
|
// Fallback: Standard-Fehlerausgabe
|
||||||
return (new Response())->withJson([
|
return (new Response())->withJson([
|
||||||
'error' => 'Internal Server Error',
|
'error' => 'Internal Server Error',
|
||||||
'message' => $e->getMessage()
|
'message' => $e->getMessage()
|
||||||
|
|
@ -241,7 +238,7 @@ class Router
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all registered routes.
|
* Gibt alle registrierten Routen zurück.
|
||||||
*
|
*
|
||||||
* @return array
|
* @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 string $prefix
|
||||||
* @param callable $callback
|
* @param callable $callback
|
||||||
|
|
@ -268,9 +265,7 @@ class Router
|
||||||
array_pop($this->groupStack);
|
array_pop($this->groupStack);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Benannte Route registrieren (intern). */
|
||||||
* Register a named route (internal use).
|
|
||||||
*/
|
|
||||||
public function nameRoute(string $name, string $method, string $pattern): void
|
public function nameRoute(string $name, string $method, string $pattern): void
|
||||||
{
|
{
|
||||||
$this->namedRoutes[$name] = [
|
$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 string $name
|
||||||
* @param array $params
|
* @param array $params
|
||||||
|
|
@ -292,7 +287,7 @@ class Router
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
$pattern = $this->namedRoutes[$name]['pattern'];
|
$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) {
|
$url = preg_replace_callback('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', function ($matches) use (&$params) {
|
||||||
$key = $matches[1];
|
$key = $matches[1];
|
||||||
if (isset($params[$key])) {
|
if (isset($params[$key])) {
|
||||||
|
|
@ -302,7 +297,7 @@ class Router
|
||||||
}
|
}
|
||||||
return $matches[0];
|
return $matches[0];
|
||||||
}, $pattern);
|
}, $pattern);
|
||||||
// Add remaining params as query string
|
// Übrige Parameter als Query-String anhängen
|
||||||
if (!empty($params)) {
|
if (!empty($params)) {
|
||||||
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($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
|
* @param callable $middleware
|
||||||
* @return void
|
* @return void
|
||||||
|
|
@ -320,9 +315,7 @@ class Router
|
||||||
$this->globalMiddleware[] = $middleware;
|
$this->globalMiddleware[] = $middleware;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Liefert aktuellen Prefix aus dem Group-Stack. */
|
||||||
* Get current prefix from group stack.
|
|
||||||
*/
|
|
||||||
private function getCurrentPrefix(): string
|
private function getCurrentPrefix(): string
|
||||||
{
|
{
|
||||||
$prefix = '';
|
$prefix = '';
|
||||||
|
|
@ -332,9 +325,7 @@ class Router
|
||||||
return $prefix;
|
return $prefix;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Liefert alle Middleware aus dem Group-Stack. */
|
||||||
* Get all middleware from group stack.
|
|
||||||
*/
|
|
||||||
private function getCurrentGroupMiddleware(): array
|
private function getCurrentGroupMiddleware(): array
|
||||||
{
|
{
|
||||||
$all = [];
|
$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<id>[^/]+)$#
|
* Beispiel: /user/{id} => #^/user/(?P<id>[^/]+)$#
|
||||||
*
|
*
|
||||||
* @param string $pattern
|
* @param string $pattern
|
||||||
* @param array &$params
|
* @param array &$params
|
||||||
|
|
@ -357,7 +348,7 @@ class Router
|
||||||
*/
|
*/
|
||||||
private function convertPatternToRegex(string $pattern, array &$params): string
|
private function convertPatternToRegex(string $pattern, array &$params): string
|
||||||
{
|
{
|
||||||
// Allow constraints: {param:regex}
|
// Constraints erlauben: {param:regex}
|
||||||
$regex = preg_replace_callback(
|
$regex = preg_replace_callback(
|
||||||
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(:([^}]+))?\}#',
|
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(:([^}]+))?\}#',
|
||||||
function ($matches) use (&$params) {
|
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 string $routeName
|
||||||
* @param array $params
|
* @param array $params
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue