routes; foreach ($segments as $segment) { // skip an empty segment, which allows us to register handlers for the root node if ($segment === '') continue; $node = &$node[$segment]; // build the node tree as we go } // Add the handler to the last node $node[$method] = $handler; return $this; } /** * Lookup a route in the router. This method will return the handler for the route if it is found, or a 404 or 405 * status code if the route is not found or the method is not allowed. If the route contains dynamic segments, the * method will return an array with the handler and the dynamic segments. * * @return [callable, array] | int */ public function lookup(string $method, string $uri): int|array { // node is a reference to our current location in the node tree $node = $this->routes; // params will hold any dynamic segments we find $params = []; // 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 404; } // if we fail to find a handler for the method, return 405 if (!isset($node[$method])) return 405; // return the handler and any dynamic segments we found return [$node[$method], $params]; } public function clear(): Router { $this->routes = []; return $this; } }