IPcalc-u-later/src/Routing/RouteCollection.php
2024-11-27 20:07:22 +01:00

91 lines
No EOL
2.1 KiB
PHP

<?php
namespace Core\Routing;
class RouteCollection
{
/**
* A majestic vault of all defined routes.
*
* @var array
*/
protected static array $routes = [];
/**
* Add a route to the sacred collection.
*
* @param string $route
* @param string $controller
* @param string $action
* @param string $method
* @return void
*/
public static function register(string $route, string $controller, string $action, string $method): void
{
// Transform human-readable route syntax into regex.
$routeRegex = self::convertToRegex($route);
// Store the route in the sacred collection
self::$routes[$method][$routeRegex] = [
'controller' => $controller,
'action' => $action,
'original' => $route,
];
}
/**
* Reveal the treasure trove of routes.
*
* @return array
*/
public static function retrieve(): array
{
return self::$routes;
}
/**
* Convert a route pattern into a regex for matching requests.
*
* @param string $route
* @return string
*/
protected static function convertToRegex(string $route): string
{
$regex = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<\1>[a-zA-Z0-9_-]+)', $route);
return '#^' . $regex . '$#';
}
/**
* Retrieve a specific route by method and URL.
*
* @param string $method
* @param string $url
* @return array|null
*/
public static function find(string $method, string $url): ?array
{
foreach (self::$routes[$method] ?? [] as $routeRegex => $route) {
if (preg_match($routeRegex, $url, $matches)) {
$route['params'] = array_filter(
$matches,
fn($key) => !is_numeric($key),
ARRAY_FILTER_USE_KEY
);
return $route;
}
}
return null;
}
/**
* Purge all routes from the collection.
*
* @return void
*/
public static function clear(): void
{
self::$routes = [];
}
}