routes; foreach ($segments as $segment) $node = &$node[$segment]; // Add the handler to the last node $node[$method] = $handler; } public function lookup(string $method, string $uri): int { // Expand the URI into segments $uriSegments = explode('/', trim($uri, '/')); $node = $this->routes; $params = []; // Traverse the routes array to find the handler foreach ($uriSegments as $segment) { // Check if the segment exists in the node, or if there's a dynamic segment if (!isset($node[$segment])) { $dynamicSegment = $this->matchDynamicSegment($node, $segment); if ($dynamicSegment) { $params[] = $segment; $node = $node[$dynamicSegment]; } else { return 404; } } else { $node = $node[$segment]; } } // If the HTTP method is not supported, return 405 if (!isset($node[$method])) return 405; // Call the handler $handler = $node[$method]; call_user_func_array($handler, $params); return 200; } private function matchDynamicSegment(array $node, string $segment) { foreach ($node as $key => $value) { if (strpos($key, ':') === 0) return $key; } return null; } }