aboutsummaryrefslogtreecommitdiff
path: root/Psso/Router.php
diff options
context:
space:
mode:
Diffstat (limited to 'Psso/Router.php')
-rw-r--r--Psso/Router.php66
1 files changed, 66 insertions, 0 deletions
diff --git a/Psso/Router.php b/Psso/Router.php
new file mode 100644
index 0000000..db1f851
--- /dev/null
+++ b/Psso/Router.php
@@ -0,0 +1,66 @@
+<?php
+namespace Psso;
+
+class Router {
+ private array $config;
+ private string $routesDir;
+ private array $statusHandlers = [];
+ private \Closure $exceptionHandler;
+
+ function __construct(string $routesDir, array $config) {
+ $this->routesDir = $routesDir;
+ $this->config = $config;
+ }
+
+ function registerStatusHandler(int $status, callable $handler) {
+ $this->statusHandlers[$status] = $handler;
+ }
+
+ function setExceptionHandler(callable $handler) {
+ $this->exceptionHandler = \Closure::fromCallable($handler);
+ }
+
+ private function dealWithError(int $status, string $path) {
+ http_response_code($status);
+ if (isset($this->statusHandlers[$status])) {
+ $this->statusHandlers[$status]($path);
+ } else {
+ echo '<p>' . $status . ' for ' . htmlspecialchars($path) . '</p>';
+ }
+ }
+
+ private function dealWithException(\Throwable $e) {
+ http_response_code(500);
+ if (isset($this->exceptionHandler)) {
+ ($this->exceptionHandler)($e);
+ } else {
+ echo '<p>Internal Server Error</p>';
+ }
+ }
+
+ function dispatch(string $path) {
+ if (str_contains($path, '..')) {
+ $this->dealWithError(404, $path);
+ return;
+ }
+
+ if (file_exists($this->routesDir . $path . '.php')) {
+ require_once $this->routesDir . $path . '.php';
+ } elseif (file_exists($this->routesDir . $path . 'index.php')) {
+ require_once $this->routesDir . $path . 'index.php';
+ } else {
+ $this->dealWithError(404, $path);
+ return;
+ }
+
+ if (function_exists($_SERVER['REQUEST_METHOD'])) {
+ try {
+ $_SERVER['REQUEST_METHOD']($this->config);
+ } catch (\Exception|\Error $e) {
+ $this->dealWithException($e);
+ }
+ } else {
+ $this->dealWithError(405, $path);
+ }
+ }
+}