Compare commits

..

No commits in common. "9e35166eeae968b538fa6a35c378dc3310d5b490" and "90b8049dc4c50f5b7e3526510ea1fb7827281691" have entirely different histories.

6 changed files with 48 additions and 17 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): array;
public function lookup(string $method, string $uri): int|array;
}

View File

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

View File

@ -2,7 +2,24 @@
class StaticRouter
{
public static function lookup(array $node, string $method, string $uri): int|array
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
{
$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): array
public function lookup(string $method, string $uri): int|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 ['code' => 404];
return 404;
}
}
}
// Check if a handler exists for the current node
if (isset($node['_handler'])) return ['code' => 200, 'handler' => $node['_handler'], 'params' => $params];
if (isset($node['_handler'])) return [$node['_handler'], $params];
return ['code' => 404];
return 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['code'] !== 200) {
if ($res === 404 || $res === 405) {
echo "Failed to handle request for $uri - $res\n";
exit(1);
}
$res['handler'](...$res['params']);
$res[0](...$res[1]);
}

View File

@ -140,8 +140,8 @@ function runIterations(int $iterations, $r, array $routes) {
}
// if any error was encountered, print it and exit
if ($res['code'] !== 200) {
echo Color::red("Failed to handle request.\n$method {$res['code']}\n"."├─ URI: $uri\n└─ Path: $path\n");
if ($res === 404 || $res === 405) {
echo Color::red("Failed to handle request.\n$method $res\n"."├─ URI: $uri\n└─ Path: $path\n");
echo Color::yellow("Completed $i iterations before failure.\n");
exit(1);
}
@ -175,6 +175,7 @@ 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
@ -183,6 +184,7 @@ 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);
}