200, 'handler' => $node[$method], 'params' => null] : ['code' => 405, 'handler' => null, 'params' => null]; } // We'll split up the URI into segments and traverse the node tree foreach (explode('/', trim($uri, '/')) as $segment) { // if there is a node for this segment, move to it if (isset($node[$segment])) { $node = $node[$segment]; continue; } // if there is a dynamic segment, move to it and store the value if (isset($node[':x'])) { $params[] = $segment; $node = $node[':x']; continue; } // if we can't find a node for this segment, return 404 return ['code' => 404, 'handler' => null, 'params' => []]; } // if we found a handler for the method, return it and any params. if not, return a 405 return isset($node[$method]) ? ['code' => 200, 'handler' => $node[$method], 'params' => $params ?? []] : ['code' => 405, 'handler' => null, 'params' => []]; } /** * Register a GET route */ function router_get(array &$routes, string $route, callable $handler): void { router_add($routes, 'GET', $route, $handler); } /** * Register a POST route */ function router_post(array &$routes, string $route, callable $handler): void { router_add($routes, 'POST', $route, $handler); } /** * Register a PUT route */ function router_put(array &$routes, string $route, callable $handler): void { router_add($routes, 'PUT', $route, $handler); } /** * Register a DELETE route */ function router_delete(array &$routes, string $route, callable $handler): void { router_add($routes, 'DELETE', $route, $handler); } /** * Register a PATCH route */ function router_patch(array &$routes, string $route, callable $handler): void { router_add($routes, 'PATCH', $route, $handler); } /** * Handle a router error by setting the response code and echoing an error message */ function router_error(int $code): void { http_response_code($code); echo match ($code) { 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 418 => 'I\'m a teapot', default => 'Unknown Error', }; exit; }