forked from PHP/Router
80 lines
2.4 KiB
PHP
80 lines
2.4 KiB
PHP
<?php
|
|
|
|
class SegmentRouter implements Router
|
|
{
|
|
public array $routes = [];
|
|
|
|
/**
|
|
* Add a route to the router. The route can contain dynamic segments, which are denoted by a colon. They are
|
|
* inserted into the node tree per segment; if a segment is dynamic, it is stored under the key ':x'.
|
|
*/
|
|
public function add(string $method, string $route, callable $handler): Router
|
|
{
|
|
// Expand the route into segments and make dynamic segments into a common placeholder
|
|
$segments = array_map(function($segment) {
|
|
return str_starts_with($segment, ':') ? ':x' : $segment;
|
|
}, explode('/', trim($route, '/')));
|
|
|
|
// Push each segment into the routes array as a node, except if this is the root node
|
|
$node = &$this->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;
|
|
}
|
|
}
|