routes; foreach ($segments as $segment) $node = &$node[$segment]; // Add the handler to the last node $node[$method] = $handler; return $this; } public function lookup(string $method, string $uri): int|array { // 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 if (isset($node[$segment])) { $node = $node[$segment]; } else { // Handle dynamic segments (starting with ":") $dynamicSegment = null; // Loop through the node and find the first dynamic segment foreach ($node as $k => $v) { if (str_starts_with($k, ':')) { $dynamicSegment = $k; break; // Break early as we only need one match } } // If no dynamic segment was found, return 404 if ($dynamicSegment === null) return 404; // Otherwise, store the parameter and move to the dynamic node $params[] = $segment; $node = $node[$dynamicSegment]; } } // Check if the HTTP method is supported if (!isset($node[$method])) return 405; // Return the handler and parameters return [$node[$method] , $params]; } public function clear(): Router { $this->routes = []; return $this; } }