Compare commits

..

10 commits

18 changed files with 1116 additions and 218 deletions

145
AGENDS.md
View file

@ -2,39 +2,138 @@
## Aufgaben & ToDos für MariaCore Router-Framework ## Aufgaben & ToDos für MariaCore Router-Framework
### Geplante Features ### Geplante Features (Stand: ✔️ = erledigt, 2024-06-15)
1. **Middleware-Unterstützung** 1. **Middleware-Unterstützung** ✔️
- Globale Middleware - Globale Middleware ✔️
- Routen-spezifische Middleware - Routen-spezifische Middleware ✔️
2. **Route-Gruppen und Prefixes** 2. **Route-Gruppen und Prefixes** ✔️
- Gruppierung von Routen mit gemeinsamen Prefixes und/oder Middleware - Gruppierung von Routen mit gemeinsamen Prefixes und/oder Middleware ✔️
3. **HTTP-Methoden erweitern** 3. **HTTP-Methoden erweitern** ✔️
- Unterstützung für PUT, DELETE, PATCH, OPTIONS - Unterstützung für PUT, DELETE, PATCH, OPTIONS ✔️
4. **Named Routes & URL-Generator** 4. **Named Routes & URL-Generator** ✔️
- Routen können benannt werden - Routen können benannt werden ✔️
- URLs können anhand des Namens generiert werden - URLs können anhand des Namens generiert werden ✔️
5. **Parameter-Validierung & Constraints** 5. **Parameter-Validierung & Constraints** ✔️
- Parameter können mit Regex validiert werden - Parameter können mit Regex validiert werden ✔️
6. **Error Handling & Custom Error Pages** 6. **Error Handling & Custom Error Pages** ✔️
- Zentrale Fehlerbehandlung, eigene Fehlerseiten/JSON - Zentrale Fehlerbehandlung, eigene Fehlerseiten/JSON ✔️
7. **Request- und Response-Helper** 7. **Request- und Response-Helper** ✔️
- Methoden wie withRedirect, withHtml, withText, withDownload - Methoden wie withRedirect, withHtml, withText, withDownload, withJson, withStatus, withHeader, withBody ✔️
8. **Controller-Support** 8. **Controller-Support** ✔️
- Handler können auch als Controller@Methode angegeben werden - Handler können auch als Controller@Methode, [Controller::class, 'methode'] oder Closure angegeben werden ✔️
9. **Routen-Caching** 9. **Routen-Caching** ✔️
- Optional: Routenstruktur als Cache speichern und laden - Optional: Routenstruktur als Cache speichern und laden (Meta-Cache, keine Closures) ✔️
- CLI-Tool zur Verwaltung ✔️
10. **Routen-Dokumentation** 10. **Routen-Dokumentation** ✔️
- Automatische Übersicht aller Routen als HTML oder JSON - Automatische Übersicht aller Routen als HTML oder JSON ✔️
- CLI-Listing ✔️
---
### Erweiterte/Neue Features (2024-06-XX)
- **Internes Forwarding:**
- Mit `Router::forward()` können Handler/Middleware intern auf andere benannte Routen weiterleiten (inkl. Query-Params). ✔️
- **Mini-Container:**
- Beispiel für einfachen Dependency Injection Container in README.md ✔️
- **CLI-Tools:**
- Routen-Cache löschen, neu bauen, anzeigen, alle Routen auflisten ✔️
- **Response-Methoden-Übersicht:**
- Alle Response-Helper und Getter in README.md dokumentiert ✔️
---
### Core-Status & optionale Features
**Aktueller Stand (Juni 2024):**
- Routing-Logik (GET, POST, PUT, PATCH, DELETE, OPTIONS)
- Middleware (global, pro Route, pro Gruppe)
- Route-Gruppen & Prefixes
- Named Routes & URL-Generator
- Parameter-Constraints (Regex)
- Controller- und Closure-Support
- Response-Helper (JSON, HTML, Text, Redirect, Download, Status, Header, Body)
- Zentrale Fehlerbehandlung (custom Error Handler)
- Routen-Caching (Meta-Cache, keine Closures)
- Internes Forwarding (kein Redirect)
- CLI-Tool für Cache & Routen
- Klar strukturierte Klassen, PHPDoc, Typisierung
**Optional für die Zukunft:**
- PSR-7/PSR-15-Kompatibilität (echte Interfaces für Requests, Responses, Middleware)
- PSR-11-Container-Integration (setContainer/getContainer im Router, automatische Controller-Instanziierung)
- Route-Parameter-Defaults
- Subdomain/Host-basiertes Routing (Multi-Tenancy)
- Mehrsprachigkeit/Locale-Routing (z.B. /de/, /en/)
- Routenpriorität/Sortierung
- Events/Hooks (vor/nach Dispatch, Middleware etc.)
- Request/Response-Validierung (z.B. JSON-Schema)
- Rate Limiting/Throttling (API-Limits)
- Tests im Core (Unit/Integration)
---
### Offene ToDos & Ideen für später
- **Remote-Repository & Push:**
- Push zu origin/dev, falls noch nicht geschehen (Remote ggf. einrichten).
- **Automatisierte Tests:**
- Unit- und Integrationstests für Router, Middleware, Response, etc. ergänzen.
- Teststrategie und Coverage festlegen.
- **CI/CD-Setup:**
- Automatisierte Checks (z.B. GitHub Actions, GitLab CI) für Linting, Tests, Composer Validate.
- **Release/Tag:**
- Stand als Release markieren, ggf. Tagging einführen.
- **Composer-Paket:**
- Veröffentlichung als Composer-Package prüfen/vorbereiten.
- **OpenAPI/Swagger:**
- Maschinenlesbare API-Dokumentation (OpenAPI/Swagger) ergänzen.
- **Demo/Framework-Trennung:**
- Demo-App und Framework ggf. in getrennte Repos auslagern.
- **Security-Review:**
- Optional: Security-Check (Header, Input-Validierung, etc.), falls öffentlich genutzt.
- **Weitere Doku/Beispiele:**
- Noch mehr Praxisbeispiele, Security-Hinweise, FAQ, Troubleshooting.
---
<!-- Stand Juni 2024: Alle Kernfeatures und Erweiterungen umgesetzt. Weitere Verbesserungen und Ideen siehe oben. -->
### 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).
- **Abschluss Stand:** Alle Kernfeatures und Erweiterungen Stand Juni 2024 umgesetzt und dokumentiert. 🎉
---
### 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.
--- ---

54
CHANGELOG.md Normal file
View 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.
---

399
README.md
View file

@ -20,6 +20,61 @@ Ein schlanker, moderner PHP-Router mit Middleware, Named Routes, Controller-Supp
--- ---
## 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 +113,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 +167,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,23 +179,73 @@ $router->group('/api', function ($router) {
$router->post('/users', [UserController::class, 'create']); $router->post('/users', [UserController::class, 'create']);
}); });
``` ```
---
## 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, keine neue URL im Browser).**
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
// In example/routes/web.php
// Leitet intern auf die named route 'user.profile' weiter, id=99, foo=bar
$router->get('/forward-demo', function (Request $request, array $params) use ($router) {
return $router->forward('user.profile', ['id' => 99], ['foo' => 'bar']);
});
```
Das Ergebnis ist identisch zu einem Aufruf von `/user/99?foo=bar`, aber ohne dass der Client weitergeleitet wird.
--- ---
## Response-Methoden
## Response-Helper Die Response-Klasse bietet folgende Methoden:
| Methode | Beschreibung | Beispiel |
|--------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|-----------------------------------------------|
| `withJson($data, $statusCode = 200, $jsonOptions = 0)` | Antwort als JSON, setzt Content-Type automatisch | `$response->withJson(['ok' => true])` |
| `withHtml($html, $statusCode = 200)` | Antwort als HTML, setzt Content-Type automatisch | `$response->withHtml('<h1>Hello</h1>')` |
| `withText($text, $statusCode = 200)` | Antwort als Plaintext, setzt Content-Type automatisch | `$response->withText('Nur Text')` |
| `withRedirect($location, $statusCode = 302)` | HTTP-Redirect, setzt Location-Header und Statuscode | `$response->withRedirect('/login')` |
| `withDownload($filename, $content, $contentType = 'application/octet-stream')` | Antwort als Datei-Download, setzt passende Header | `$response->withDownload('file.txt', 'Inhalt')`|
| `withStatus($code)` | Antwort mit anderem HTTP-Statuscode (z.B. 404, 500) | `$response->withStatus(404)` |
| `withHeader($name, $value)` | Setzt einen beliebigen HTTP-Header | `$response->withHeader('X-Test', 'Wert')` |
| `withBody($body)` | Antwort mit anderem Body | `$response->withBody('Neuer Body')` |
| `getStatusCode()` | Gibt den aktuellen HTTP-Statuscode zurück | `$response->getStatusCode()` |
| `getHeaders()` | Gibt alle gesetzten Header als Array zurück | `$response->getHeaders()` |
| `getBody()` | Gibt den aktuellen Body zurück | `$response->getBody()` |
| `send()` | Sendet die Antwort an den Client (wird meist automatisch am Ende aufgerufen) | `$response->send()` |
### Beispiele
```php ```php
<?php <?php
return (new Response())->withJson(['ok' => true]); // JSON-Antwort
return (new Response())->withHtml('<h1>Hello</h1>'); return (new Response())->withJson(['success' => true]);
// HTML-Antwort
return (new Response())->withHtml('<h1>Hallo Welt!</h1>');
// Plaintext
return (new Response())->withText('Nur Text'); return (new Response())->withText('Nur Text');
// Redirect
return (new Response())->withRedirect('/login'); return (new Response())->withRedirect('/login');
return (new Response())->withDownload('datei.txt', 'Inhalt...'); // Datei-Download
return (new Response())->withDownload('beispiel.txt', 'Dateiinhalt', 'text/plain');
// Statuscode ändern
return (new Response())->withStatus(404)->withText('Nicht gefunden');
// Header setzen
return (new Response())->withHeader('X-Custom', 'Wert')->withJson(['ok' => true]);
// Statuscode, Header und Body abfragen
$status = $response->getStatusCode();
$headers = $response->getHeaders();
$body = $response->getBody();
``` ```
--- ---
@ -164,49 +292,79 @@ function (Request $request, array $params)
--- ---
## Response-Methoden ## API-Dokumentation
Die Response-Klasse bietet folgende Methoden: Hier findest du eine Übersicht aller Beispiel- und API-Endpunkte, wie sie in der Demo-Anwendung (`example/routes/web.php`) und Insomnia-Collection enthalten sind.
| Methode | Beschreibung | Beispiel | ### Übersicht
|--------------------------|-----------------------------------------------------------------------------------------------|-----------------------------------------------|
| `withJson($data, $statusCode = 200)` | Antwort als JSON, setzt Content-Type automatisch | `$response->withJson(['ok' => true])` |
| `withHtml($html, $statusCode = 200)` | Antwort als HTML, setzt Content-Type automatisch | `$response->withHtml('<h1>Hello</h1>')` |
| `withText($text, $statusCode = 200)` | Antwort als Plaintext, setzt Content-Type automatisch | `$response->withText('Nur Text')` |
| `withRedirect($location, $statusCode = 302)` | HTTP-Redirect, setzt Location-Header und Statuscode | `$response->withRedirect('/login')` |
| `withDownload($filename, $content, $contentType = 'application/octet-stream')` | Antwort als Datei-Download, setzt passende Header | `$response->withDownload('file.txt', 'Inhalt')`|
| `withStatus($code)` | Antwort mit anderem HTTP-Statuscode (z.B. 404, 500) | `$response->withStatus(404)` |
| `withHeader($name, $value)`| Setzt einen beliebigen HTTP-Header | `$response->withHeader('X-Test', 'Wert')` |
| `withBody($body)` | Antwort mit anderem Body | `$response->withBody('Neuer Body')` |
| `send()` | Sendet die Antwort an den Client (wird meist automatisch am Ende aufgerufen) | `$response->send()` |
### Beispiele | Methode | Pfad | Beschreibung | Auth/Middleware | Beispiel-Response |
|---------|-----------------------------|----------------------------------------------|------------------------|-------------------------------|
| GET | `/` | Startseite (HTML) | – | `<h1>Willkommen!</h1>` |
| GET | `/routes` | Alle Routen als JSON | – | JSON-Array aller Routen |
| GET | `/routes.html` | Alle Routen als HTML-Tabelle | – | HTML-Tabelle |
| GET | `/hello/{name}` | Begrüßung mit Name (HTML) | – | `<h1>Hallo aus dem Controller, ...</h1>` |
| GET | `/twig-demo` | Twig-Demo: Rendert ein Template mit Config | – | HTML-Seite mit Begrüßung und Info |
| GET | `/users-from-db` | User-Liste aus SQLite-Datenbank (Demo) | – | `{ "users": [ ... ] }` |
| GET | `/user/{id}` | User-Info als JSON | – | `{ "user_id": 42, ... }` |
| GET | `/protected` | Geschützte Route (JSON) | Header: `x-auth` | 401/200 JSON |
| GET | `/go-home` | Redirect zur Startseite | – | HTTP 302 Redirect |
| GET | `/forward-demo` | Internes Forwarding auf `/user/99` | – | `{ "user_id": 99, ... }` |
| GET | `/plain` | Plaintext-Antwort | – | `Dies ist eine reine Textantwort.` |
| GET | `/download` | Datei-Download | – | Download |
| POST | `/users` | User anlegen (Demo) | – | `{ "message": "User created" }`|
| POST | `/submit` | Formular-Submit (Demo) | – | HTML |
| PUT | `/users/{id}` | User aktualisieren (Demo) | – | `{ "message": "User updated", ... }` |
| PATCH | `/users/{id}` | User Teil-Update (Demo) | – | `{ "message": "User partially updated", ... }` |
| DELETE | `/users/{id}` | User löschen (Demo) | – | `{ "message": "User deleted", ... }` |
| OPTIONS | `/users` | Unterstützte Methoden für /users | – | Header + JSON |
```php #### API-Gruppe `/api`
<?php
// JSON-Antwort | Methode | Pfad | Beschreibung | Beispiel-Response |
return (new Response())->withJson(['success' => true]); |---------|-----------------------|---------------------------------|-------------------------------|
| GET | `/api/users` | Alle User (Demo) | `{ "users": [...] }` |
| POST | `/api/users` | User anlegen (Demo) | `{ "message": "User created" }`|
| PUT | `/api/users/{id}` | User aktualisieren (Demo) | `{ "message": "User updated", "id": ... }` |
| PATCH | `/api/users/{id}` | User Teil-Update (Demo) | `{ "message": "User partially updated", "id": ... }` |
| PATCH | `/api/users` | Teil-Update aller User (Demo) | `{ "message": "Alle User wurden ..."} ` |
| DELETE | `/api/users/{id}` | User löschen (Demo) | `{ "message": "User deleted", "id": ... }` |
| OPTIONS | `/api/users` | Unterstützte Methoden | Header + JSON |
| GET | `/api/users/{id}` | User-Info (Demo) | `{ "user_id": ..., ... }` |
| OPTIONS | `/api/users/{id}` | Unterstützte Methoden | Header + JSON |
// HTML-Antwort #### Admin-Gruppe `/admin`
return (new Response())->withHtml('<h1>Hallo Welt!</h1>');
// Plaintext | Methode | Pfad | Beschreibung | Auth/Middleware | Beispiel-Response |
return (new Response())->withText('Nur Text'); |---------|-----------------------|---------------------------------|-------------------------------|-------------------------------|
| GET | `/admin/dashboard` | Admin-Dashboard (Demo) | Header: `x-admin: true` | `{ "dashboard": "Admin stats here" }` |
// Redirect ---
return (new Response())->withRedirect('/login');
// Datei-Download ### Hinweise
return (new Response())->withDownload('beispiel.txt', 'Dateiinhalt', 'text/plain');
// Statuscode ändern - **Parameter:**
return (new Response())->withStatus(404)->withText('Nicht gefunden'); Platzhalter wie `{id}` oder `{name}` werden automatisch aus der URL extrahiert und als `$params` übergeben.
- **Middleware:**
Einige Endpunkte (z.B. `/protected`, `/admin/dashboard`) erfordern spezielle Header für Authentifizierung.
- **Response-Formate:**
Die meisten Endpunkte liefern JSON, einige HTML oder Plaintext. Datei-Downloads werden mit passenden Headern ausgeliefert.
- **Twig-Demo:**
Der Pfad `/twig-demo` zeigt, wie ein Twig-Template mit Variablen und Config gerendert wird.
- **SQLite/PDO-Demo:**
Der Pfad `/users-from-db` gibt User-Daten aus der SQLite-Datenbank zurück (Tabelle `users` muss existieren, siehe Setup).
- **Weitere Beispiele und Testmöglichkeiten:**
Siehe die beiliegende Insomnia-Collection (`example/insomnia.json`).
// Header setzen ---
return (new Response())->withHeader('X-Custom', 'Wert')->withJson(['ok' => true]);
```
## 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.
--- ---
@ -230,6 +388,22 @@ return (new Response())->withHeader('X-Custom', 'Wert')->withJson(['ok' => true]
- **Alle Routen auflisten:** - **Alle Routen auflisten:**
`bin/route-cache list` `bin/route-cache list`
### CLI-Tool verwenden
Das CLI-Tool findest du unter `bin/route-cache`. Du kannst es so aufrufen:
```bash
php bin/route-cache list
# oder (wenn du es mit chmod +x bin/route-cache unter Linux/MacOS ausführbar gemacht hast)
bin/route-cache list
```
Verfügbare Befehle:
- `build` – Cache neu generieren
- `clear` – Cache löschen
- `show` – Cache anzeigen (JSON)
- `list` – Alle registrierten Routen anzeigen
--- ---
## Projektstruktur ## Projektstruktur
@ -240,12 +414,8 @@ example/ # Demo-Anwendung (Controller, Routen, Public)
bin/ # CLI-Tools bin/ # CLI-Tools
cache/ # Routen-Cache (JSON) cache/ # Routen-Cache (JSON)
``` ```
--- ---
## Dependency Injection & Mini-Container ## Dependency Injection & Mini-Container
Du kannst dein Projekt mit einem einfachen Dependency Injection Container (DI-Container) noch flexibler machen. Damit kannst du Controller, Services oder Middleware automatisch instanziieren und Abhängigkeiten verwalten. Du kannst dein Projekt mit einem einfachen Dependency Injection Container (DI-Container) noch flexibler machen. Damit kannst du Controller, Services oder Middleware automatisch instanziieren und Abhängigkeiten verwalten.
@ -313,15 +483,130 @@ $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.
--- ---
## Template-Engines (z.B. Twig) integrieren
Du kannst beliebige Template-Engines wie [Twig](https://twig.symfony.com/) einfach nutzen – direkt im Handler oder (empfohlen) über einen DI-Container.
### Twig installieren
```bash
composer require twig/twig
```
### Twig im Handler verwenden
```php
<?php
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
$twig = new Environment(new FilesystemLoader(__DIR__ . '/../templates'));
$router->get('/hello/{name}', function (Request $request, array $params) use ($twig) {
$name = $params['name'] ?? 'Gast';
$html = $twig->render('hello.html.twig', ['name' => $name]);
return (new Response())->withHtml($html);
});
```
### Twig im Controller via Container (empfohlen)
```php
<?php
// Registrierung im Container
$container->set(Environment::class, fn($c) => new Environment(
new FilesystemLoader(__DIR__ . '/../templates')
));
// Controller
use Twig\Environment;
class HelloController {
protected Environment $twig;
public function __construct(Environment $twig) {
$this->twig = $twig;
}
public function greet(Request $request, array $params) {
$name = $params['name'] ?? 'Gast';
$html = $this->twig->render('hello.html.twig', ['name' => $name]);
return (new Response())->withHtml($html);
}
}
// Handler-Registrierung
$router->get('/hello/{name}', [HelloController::class, 'greet']);
```
### Twig-Template (z.B. `example/templates/hello.html.twig`)
```twig
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hallo, {{ name }}!</h1>
</body>
</html>
```
---
## Datenbank-Anbindung (PDO/Doctrine/...)
Du kannst beliebige Datenbank-Clients (z.B. PDO, Doctrine DBAL, Medoo) direkt im Handler oder – besser – über einen DI-Container nutzen.
**PDO im Handler:**
```php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=demo', 'user', 'pass');
$router->get('/users', function (Request $request, array $params) use ($pdo) {
$users = $pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);
return (new Response())->withJson(['users' => $users]);
});
```
**PDO im Controller via Container:**
```php
<?php
$container->set(PDO::class, fn($c) => new PDO('mysql:host=localhost;dbname=demo', 'user', 'pass'));
class UserController {
protected PDO $pdo;
public function __construct(PDO $pdo) { $this->pdo = $pdo; }
public function list(Request $request, array $params) {
$users = $this->pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);
return (new Response())->withJson(['users' => $users]);
}
}
$router->get('/users', [UserController::class, 'list']);
```
**Doctrine DBAL im Container:**
```php
<?php
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
$container->set(Connection::class, fn($c) => DriverManager::getConnection([
'url' => 'mysql://user:pass@localhost/demo'
]));
```
---
## Lizenz ## Lizenz

51
bin/reset-demo-db.php Normal file
View file

@ -0,0 +1,51 @@
<?php
// bin/reset-demo-db.php
// Setzt die SQLite-Datenbank zurück und legt sie mit Demo-Tabelle 'users' und Beispiel-Daten neu an.
$dbFile = __DIR__ . '/../database.sqlite';
if (file_exists($dbFile)) {
echo "Lösche bestehende Datenbank: $dbFile\n";
if (!unlink($dbFile)) {
echo "Fehler: Konnte alte Datenbank nicht löschen!\n";
exit(1);
}
}
try {
$pdo = new PDO('sqlite:' . $dbFile);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Tabelle anlegen
$pdo->exec("
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
);
");
// Demo-Daten einfügen
$users = [
['Alice', 'alice@example.com'],
['Bob', 'bob@example.com'],
['Charlie', 'charlie@example.com'],
['Dora', 'dora@example.com'],
['Eve', 'eve@example.com'],
];
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
foreach ($users as $user) {
$stmt->execute($user);
}
echo "SQLite-Datenbank wurde zurückgesetzt und neu erstellt: $dbFile\n";
echo "Tabelle 'users' mit Demo-Daten angelegt.\n";
} catch (Throwable $e) {
echo "Fehler beim Erstellen der Datenbank: " . $e->getMessage() . "\n";
if (file_exists($dbFile)) {
unlink($dbFile);
}
exit(1);
}

View file

@ -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;

View file

@ -2,7 +2,9 @@
"name": "mycodebox/mariacore", "name": "mycodebox/mariacore",
"description": "Ein einfacher, PSR-inspirierter PHP-Router", "description": "Ein einfacher, PSR-inspirierter PHP-Router",
"type": "project", "type": "project",
"require": {}, "require": {
"twig/twig": "^3.23"
},
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"MyCodebox\\MariaCore\\": "src/", "MyCodebox\\MariaCore\\": "src/",
@ -17,7 +19,6 @@
"sort-packages": true, "sort-packages": true,
"process-timeout": 0 "process-timeout": 0
}, },
"require-dev": {},
"license": "MIT", "license": "MIT",
"authors": [ "authors": [
{ {

BIN
database.sqlite Normal file

Binary file not shown.

View file

@ -4,12 +4,36 @@ namespace App\Controller;
use MyCodebox\MariaCore\Http\Request; use MyCodebox\MariaCore\Http\Request;
use MyCodebox\MariaCore\Http\Response; use MyCodebox\MariaCore\Http\Response;
use Twig\Environment;
/**
* Beispiel-Controller für Begrüßungen.
*/
class HelloController class HelloController
{ {
public function greet(Request $request, array $params) protected Environment $twig;
/**
* Konstruktor mit Twig-Dependency.
*
* @param Environment $twig
*/
public function __construct(Environment $twig)
{ {
$name = htmlspecialchars($params['name'] ?? 'Gast'); $this->twig = $twig;
return (new Response())->withHtml("<h1>Hallo aus dem Controller, {$name}!</h1>"); }
/**
* Gibt eine HTML-Begrüßung mit Twig-Template zurück.
*
* @param Request $request
* @param array $params
* @return Response
*/
public function greet(Request $request, array $params): Response
{
$name = $params['name'] ?? 'Gast';
$html = $this->twig->render('hello.html.twig', ['name' => $name]);
return (new Response())->withHtml($html);
} }
} }

View file

@ -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);

View file

@ -70,6 +70,28 @@
"headers": [], "headers": [],
"_type": "request" "_type": "request"
}, },
{
"_id": "req_twig_demo",
"parentId": "fld_demo",
"name": "Twig-Demo (Template-Rendering)",
"method": "GET",
"url": "{{ base_url }}/twig-demo",
"body": {},
"parameters": [],
"headers": [],
"description": "Rendert ein Twig-Template mit Name und Config-Info.\n\n**Erwartete Antwort:**\nHTML-Seite mit Begrüßung und Info-Text."
},
{
"_id": "req_users_from_db",
"parentId": "fld_demo",
"name": "Users from DB (SQLite/PDO)",
"method": "GET",
"url": "{{ base_url }}/users-from-db",
"body": {},
"parameters": [],
"headers": [],
"description": "Gibt User-Daten aus der SQLite-Datenbank zurück (Tabelle 'users' muss existieren).\n\n**Erwartete Antwort:**\n```\n{\n \"users\": [\n { \"id\": 1, \"name\": \"Alice\", \"email\": \"alice@example.com\" },\n ...\n ]\n}\n```\nBei Fehler: `{ \"error\": \"DB-Fehler\", \"message\": \"...\" }`"
},
{ {
"_id": "req_user", "_id": "req_user",
"parentId": "fld_demo", "parentId": "fld_demo",
@ -81,8 +103,20 @@
"headers": [], "headers": [],
"_type": "request" "_type": "request"
}, },
{
"_id": "req_forward_demo",
"parentId": "fld_demo",
"name": "Forward-Demo (internes Routing)",
"method": "GET",
"url": "{{ base_url }}/forward-demo",
"body": {},
"parameters": [],
"headers": [],
"description": "Demonstriert internes Routing (Forwarding) auf die named route 'user.profile' mit id=99 und foo=bar als Query-Parameter.\n\n**Erwartete Antwort:**\n```\n{\n \"user_id\": 99,\n \"profile_url\": \"/user/99\"\n}\n```\nDie Query-Parameter sind in der URL sichtbar, aber werden im Handler nicht verwendet."
},
{ {
"_id": "req_protected_fail", "_id": "req_protected_fail",
"parentId": "fld_demo", "parentId": "fld_demo",
"name": "Protected (ohne Auth, sollte 401 liefern)", "name": "Protected (ohne Auth, sollte 401 liefern)",
"method": "GET", "method": "GET",

View file

@ -7,21 +7,50 @@ use MyCodebox\MariaCore\Http\Request;
use MyCodebox\MariaCore\Http\Response; use MyCodebox\MariaCore\Http\Response;
use MyCodebox\MariaCore\Router; use MyCodebox\MariaCore\Router;
use MyCodebox\MariaCore\Cache\RouteCache; use MyCodebox\MariaCore\Cache\RouteCache;
use MyCodebox\MariaCore\Container;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
// -------------------------------------------------
// Container-Instanz erstellen und Services registrieren
// -------------------------------------------------
$container = new Container();
// Twig registrieren (Singleton)
$container->set(Environment::class, fn($c) => new Environment(
new FilesystemLoader(__DIR__ . '/../templates')
), true);
// PDO registrieren (Singleton, Beispiel mit SQLite)
$container->set(PDO::class, fn($c) => new PDO('sqlite:' . __DIR__ . '/../../database.sqlite'), true);
// Beispiel: Config als Wert
$container->set('config', [
'app_name' => 'MariaCore Demo',
'debug' => true
]);
// Beispiel: Controller-Registrierung (optional, kann auch automatisch erfolgen)
/*
$container->set(App\Controller\HelloController::class, fn($c) => new App\Controller\HelloController($c->get(Environment::class)));
*/
// -------------------------------------------------
// 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,14 +58,25 @@ $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
$routeCache = new RouteCache(__DIR__ . '/../../cache/routes.json'); $routeCache = new RouteCache(__DIR__ . '/../../cache/routes.json');
$routeCache->write($router->routes); $routeCache->write($router->routes);
// Beispiel: Nutzung von Services aus dem Container
// (z.B. in einem Handler, Controller oder Middleware)
/*
$twig = $container->get(Environment::class);
$pdo = $container->get(PDO::class);
$config = $container->get('config');
*/
// Request erzeugen und dispatchen // Request erzeugen und dispatchen
$request = new Request(); $request = new Request();
$response = $router->dispatch($request); $response = $router->dispatch($request);

View file

@ -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!']);
}, [ }, [
@ -35,6 +34,35 @@ $router->get('/protected', function (Request $request, array $params) {
$router->get('/hello/{name}', [HelloController::class, 'greet'])->name('hello'); $router->get('/hello/{name}', [HelloController::class, 'greet'])->name('hello');
// Twig-Demo: Rendert ein Template mit Name und Config-Wert
$router->get('/twig-demo', function (Request $request, array $params) use ($container) {
/** @var \Twig\Environment $twig */
$twig = $container->get(\Twig\Environment::class);
$config = $container->get('config');
$html = $twig->render('hello.html.twig', [
'name' => 'Twig-Demo',
'info' => 'App: ' . ($config['app_name'] ?? 'n/a')
]);
return (new Response())->withHtml($html);
});
// SQLite/PDO-Demo: Gibt User aus Datenbank zurück (Tabelle users erwartet)
$router->get('/users-from-db', function (Request $request, array $params) use ($container) {
/** @var \PDO $pdo */
$pdo = $container->get(\PDO::class);
$users = [];
try {
$stmt = $pdo->query('SELECT id, name, email FROM users');
$users = $stmt ? $stmt->fetchAll(\PDO::FETCH_ASSOC) : [];
} catch (\Throwable $e) {
return (new Response())->withJson([
'error' => 'DB-Fehler',
'message' => $e->getMessage()
], 500);
}
return (new Response())->withJson(['users' => $users]);
});
$router->get('/user/{id}', function (Request $request, array $params) use ($router) { $router->get('/user/{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]);
@ -48,6 +76,12 @@ $router->get('/go-home', function (Request $request, array $params) {
return (new Response())->withRedirect('/'); return (new Response())->withRedirect('/');
}); });
// Demo: Internes Forwarding auf /user/{id} mit Query-Params
$router->get('/forward-demo', function (Request $request, array $params) use ($router) {
// Leitet intern auf die named route 'user.profile' weiter, 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.");
}); });
@ -57,7 +91,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);
}); });
@ -68,27 +104,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']]);
@ -106,15 +154,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]);
@ -123,7 +173,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')
@ -131,6 +181,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']);

View file

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Hallo {{ name }}</title>
<style>
body { font-family: sans-serif; background: #f8f8f8; margin: 2em; }
h1 { color: #2c3e50; }
.info { color: #888; margin-top: 2em; }
</style>
</head>
<body>
<h1>Hallo, {{ name|e('html') }}!</h1>
<div class="info">
Dies ist ein Beispiel für ein Twig-Template.<br>
Du kannst beliebige Variablen und Logik verwenden.
</div>
</body>
</html>

View file

@ -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);
}
} }
} }
} }

92
src/Container.php Normal file
View file

@ -0,0 +1,92 @@
<?php
namespace MyCodebox\MariaCore;
use Closure;
use InvalidArgumentException;
/**
* Einfacher, flexibler Dependency Injection Container.
*
* Unterstützt:
* - Factory-Registrierung (immer neue Instanz)
* - Singleton-Registrierung (einmalige Instanz)
* - Direkte Werte/Objekte
* - Lazy Loading (erst bei Bedarf erzeugt)
*
* Beispiel:
* $container->set(PDO::class, fn($c) => new PDO(...), true); // Singleton
* $container->set('config', fn($c) => [...]); // Factory
* $container->set('twig', $twigInstance); // Direktes Objekt
*/
class Container
{
/**
* @var array<string, array{factory: callable, singleton: bool}>
*/
protected array $bindings = [];
/**
* @var array<string, mixed>
*/
protected array $instances = [];
/**
* Registrierung einer Factory oder eines Singleton.
*
* @param string $id
* @param callable|object $factory
* @param bool $singleton
* @return void
*/
public function set(string $id, $factory, bool $singleton = false): void
{
if (is_callable($factory)) {
$this->bindings[$id] = ['factory' => $factory, 'singleton' => $singleton];
} else {
// Direktes Objekt, Array oder Wert
$this->instances[$id] = $factory;
}
}
/**
* Hole eine Instanz (Singleton oder Factory).
*
* @param string $id
* @return mixed
*/
public function get(string $id)
{
// Singleton bereits erzeugt?
if (isset($this->instances[$id])) {
return $this->instances[$id];
}
// Factory vorhanden?
if (isset($this->bindings[$id])) {
$object = ($this->bindings[$id]['factory'])($this);
if ($this->bindings[$id]['singleton']) {
$this->instances[$id] = $object;
}
return $object;
}
// Fallback: Standard-Konstruktor (ohne Abhängigkeiten)
if (class_exists($id)) {
return new $id();
}
throw new InvalidArgumentException("Service oder Klasse '$id' nicht gefunden.");
}
/**
* Prüft, ob ein Service/Binding existiert.
*
* @param string $id
* @return bool
*/
public function has(string $id): bool
{
return isset($this->bindings[$id]) || isset($this->instances[$id]) || class_exists($id);
}
}

View file

@ -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,27 +86,61 @@ 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;
} /**
* Create a Request object with custom parameters (for internal forwarding).
*
* @param array $override ['method' => ..., 'uri' => ..., 'queryParams' => ..., 'parsedBody' => ..., 'headers' => ...]
* @return static
*/
public static function fromGlobalsOverride(array $override = []): self
{
$instance = new self();
if (isset($override['method'])) {
$instance->method = $override['method'];
} }
return null; if (isset($override['uri'])) {
$instance->uri = $override['uri'];
}
if (isset($override['queryParams'])) {
$instance->queryParams = $override['queryParams'];
}
if (isset($override['parsedBody'])) {
$instance->parsedBody = $override['parsedBody'];
}
if (isset($override['headers'])) {
// Vereinheitliche Header-Namen auf Kleinbuchstaben
$headers = [];
foreach ($override['headers'] as $key => $value) {
$headers[strtolower($key)] = $value;
}
$instance->headers = $headers;
}
return $instance;
} }
/** /**
* 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;
} }
} }

View file

@ -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;

View file

@ -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,34 +23,35 @@ class Router
'PATCH' => [], 'PATCH' => [],
'DELETE' => [], 'DELETE' => [],
'OPTIONS' => [], 'OPTIONS' => [],
// 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 = [])
{ {
@ -71,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;
@ -91,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
@ -154,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
@ -174,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)) {
@ -185,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) {
@ -231,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()
@ -240,7 +238,7 @@ class Router
} }
/** /**
* Get all registered routes. * Gibt alle registrierten Routen zurück.
* *
* @return array * @return array
*/ */
@ -250,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
@ -267,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] = [
@ -279,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
@ -291,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])) {
@ -301,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);
} }
@ -309,7 +305,7 @@ class Router
} }
/** /**
* Add global middleware. * Globale Middleware hinzufügen.
* *
* @param callable $middleware * @param callable $middleware
* @return void * @return void
@ -319,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 = '';
@ -331,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 = [];
@ -346,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
@ -356,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) {
@ -368,4 +360,30 @@ class Router
); );
return '#^' . $regex . '$#'; return '#^' . $regex . '$#';
} }
/**
* Internes Forwarding auf eine andere benannte Route (ohne HTTP-Redirect).
*
* @param string $routeName
* @param array $params
* @param array $queryParams
* @param string $method
* @return Response
*/
public function forward(string $routeName, array $params = [], array $queryParams = [], string $method = 'GET'): Response
{
$url = $this->url($routeName, $params);
// Query-String anhängen, falls vorhanden
if (!empty($queryParams)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($queryParams);
}
// Neues Request-Objekt mit gewünschter URI und Query-Params erzeugen
$forwardedRequest = \MyCodebox\MariaCore\Http\Request::fromGlobalsOverride([
'method' => $method,
'uri' => strtok($url, '?'),
'queryParams' => $queryParams,
]);
// Dispatch an den Router
return $this->dispatch($forwardedRequest);
}
} }