Compare commits

...

2 Commits

6 changed files with 17 additions and 48 deletions

View File

@ -2,5 +2,5 @@
interface Router {
public function add(string $method, string $route, callable $handler): Router;
public function lookup(string $method, string $uri): int|array;
public function lookup(string $method, string $uri): array;
}

View File

@ -4,10 +4,6 @@ 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
@ -29,14 +25,8 @@ class SegmentRouter implements Router
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
// @return array{code: int, handler: callable, params: array|null }
public function lookup(string $method, string $uri): array
{
// node is a reference to our current location in the node tree
$node = $this->routes;
@ -60,17 +50,15 @@ class SegmentRouter implements Router
}
// if we can't find a node for this segment, return 404
return 404;
return ['code' => 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];
// 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 ?? null]
: ['code' => 405];
}
public function clear(): Router
{
$this->routes = [];

View File

@ -2,24 +2,7 @@
class StaticRouter
{
public static $routes = [];
public static function add(string $method, string $route, callable $handler): void
{
$segments = array_map(function($segment) {
return str_starts_with($segment, ':') ? ':x' : $segment;
}, explode('/', trim($route, '/')));
$node = &self::$routes;
foreach ($segments as $segment) {
if ($segment === '') continue;
$node = &$node[$segment];
}
$node[$method] = $handler;
}
public static function lookup(array $node /* = &$this->routes */, string $method, string $uri): int|array
public static function lookup(array $node, string $method, string $uri): int|array
{
$uriSegments = explode('/', trim($uri, '/'));
$params = [];

View File

@ -26,7 +26,7 @@ class TrieRouter implements Router
}
// Find and handle the route
public function lookup(string $method, string $uri): int|array
public function lookup(string $method, string $uri): array
{
$node = &$this->root[$method];
$segments = explode('/', trim($uri, '/'));
@ -42,15 +42,15 @@ class TrieRouter implements Router
$params[] = $segment;
$node = &$node[$dynamicSegment]['_children'];
} else {
return 404;
return ['code' => 404];
}
}
}
// Check if a handler exists for the current node
if (isset($node['_handler'])) return [$node['_handler'], $params];
if (isset($node['_handler'])) return ['code' => 200, 'handler' => $node['_handler'], 'params' => $params];
return 404;
return ['code' => 404];
}
// Match dynamic route segments like ':id'

View File

@ -75,9 +75,9 @@ for ($i = 0; $i < 10; $i++) {
$uri = str_replace(':extra', 'extra-' . rand(1, 100), $uri);
$res = $r->lookup($method, $uri);
if ($res === 404 || $res === 405) {
if ($res['code'] !== 200) {
echo "Failed to handle request for $uri - $res\n";
exit(1);
}
$res[0](...$res[1]);
$res['handler'](...$res['params']);
}

View File

@ -140,8 +140,8 @@ function runIterations(int $iterations, $r, array $routes) {
}
// if any error was encountered, print it and exit
if ($res === 404 || $res === 405) {
echo Color::red("Failed to handle request.\n$method $res\n"."├─ URI: $uri\n└─ Path: $path\n");
if ($res['code'] !== 200) {
echo Color::red("Failed to handle request.\n$method {$res['code']}\n"."├─ URI: $uri\n└─ Path: $path\n");
echo Color::yellow("Completed $i iterations before failure.\n");
exit(1);
}
@ -175,7 +175,6 @@ function writeRoutesToFile(array $routes, string $file) {
// Clear the file before writing
file_put_contents($file, '');
// Open the file for writing
$fp = fopen($file, 'w');
// write a / to the first line of the file
@ -184,7 +183,6 @@ function writeRoutesToFile(array $routes, string $file) {
// Start writing from the root level with an indentation of 0 and no prefix
writeNode($routes, 0, '', $fp);
// Close the file
fclose($fp);
}