Dragon-Knight/server/app/App.php

78 lines
1.6 KiB
PHP

<?php
/*
The app container exists to be a dependency container for the game.
*/
class App
{
private array $routes = [];
public static Database $db;
public static Request $req;
public static Auth $auth;
public static array $s = []; // game settings
public static array $flashes = []; // flash messages
public function __construct(Database $db, Request $req, Auth $auth)
{
self::$req = $req; // the current request
self::$db = $db; // the database
self::$auth = $auth; // the auth system
// load game settings
$s = self::$db->q('SELECT * FROM settings WHERE id = 1;');
self::$s = $s ? $s->fetch() : [];
if (INSTALLED) {
// load the player's auth
self::$auth->good();
}
// load flash messages
self::$flashes = $_SESSION['flash'] ?? [];
}
public static function auth(): bool
{
return self::$auth->good();
}
public function route(string $uri, string $module): App
{
$this->routes[$uri] = $module;
return $this;
}
public function handle(string $uri): App
{
if (!isset($this->routes[$uri])) return self::fourOhFour($uri);
$this->routes[$uri]::handle();
return $this;
}
public static function flash(string $key, mixed $value = null): mixed
{
// get a flash message
if ($value === null) return self::$flashes[$key] ?? null;
// set a flash message
$_SESSION['flash'][$key] = $value;
self::$flashes[$key] = $value;
return null;
}
public function cleanup()
{
// clean up flash messages
$_SESSION['flash'] = [];
self::$flashes = [];
}
public static function fourOhFour(string $uri): void
{
http_response_code(404);
echo "404: $uri";
}
}