version 0.8.0
This commit is contained in:
parent
f22007003a
commit
e5ca9ef194
95 changed files with 5601 additions and 4042 deletions
67
app/Core/Router.php
Normal file
67
app/Core/Router.php
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Router: trennt Seiten- und API-Requests.
|
||||
* / -> Seiten-Route '' -> [Controller, method]
|
||||
* /regeln -> Seiten-Route 'regeln'
|
||||
* /api/state -> API-Route 'state' -> [Controller, method]
|
||||
* /api/auth/me -> API-Route 'auth/me'
|
||||
* Unbekannte Seite -> 404-Route; unbekannte API -> JSON-Fehler.
|
||||
*/
|
||||
final class Router
|
||||
{
|
||||
/**
|
||||
* @param array<string,array{0:class-string,1:string}> $web
|
||||
* @param array<string,array{0:class-string,1:string}> $api
|
||||
*/
|
||||
public function __construct(private array $web, private array $api) {}
|
||||
|
||||
public function dispatch(): void
|
||||
{
|
||||
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';
|
||||
$slug = trim(rawurldecode($path), '/');
|
||||
|
||||
if ($slug === 'api' || str_starts_with($slug, 'api/')) {
|
||||
$this->dispatchApi(ltrim(substr($slug, 3), '/'));
|
||||
return;
|
||||
}
|
||||
|
||||
$this->dispatchPage($slug);
|
||||
}
|
||||
|
||||
private function dispatchApi(string $action): void
|
||||
{
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
|
||||
try {
|
||||
Migrator::run(Database::pdo(), (string) Config::get('dbname'));
|
||||
} catch (Throwable $e) {
|
||||
respond(['error' => 'DB-Verbindung fehlgeschlagen: ' . $e->getMessage()], 500);
|
||||
}
|
||||
|
||||
if (!isset($this->api[$action])) {
|
||||
respond(['error' => 'Unbekannte Aktion.'], 400);
|
||||
}
|
||||
|
||||
[$class, $method] = $this->api[$action];
|
||||
try {
|
||||
(new $class())->$method();
|
||||
} catch (Throwable $e) {
|
||||
respond(['error' => 'Serverfehler: ' . $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
private function dispatchPage(string $slug): void
|
||||
{
|
||||
if (isset($this->web[$slug])) {
|
||||
$route = $this->web[$slug];
|
||||
} else {
|
||||
http_response_code(404);
|
||||
$route = $this->web['__404__'];
|
||||
}
|
||||
[$class, $method] = $route;
|
||||
(new $class())->$method();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue