77 lines
No EOL
1.8 KiB
PHP
77 lines
No EOL
1.8 KiB
PHP
<?php
|
|
|
|
namespace Core\Routing;
|
|
|
|
use Core\Http\Request;
|
|
|
|
class Router
|
|
{
|
|
/**
|
|
* List of routes
|
|
*
|
|
* @var array
|
|
*/
|
|
protected static array $routes = [];
|
|
|
|
/**
|
|
* Add GET route
|
|
*
|
|
* @param string $route
|
|
* @param string $controller
|
|
* @param string $action
|
|
* @return void
|
|
*/
|
|
public static function get(string $route, string $controller, string $action): void
|
|
{
|
|
self::register($route, $controller, $action, "GET");
|
|
}
|
|
|
|
/**
|
|
* Add POST route
|
|
*
|
|
* @param string $route
|
|
* @param string $controller
|
|
* @param string $action
|
|
* @return void
|
|
*/
|
|
public static function post(string $route, string $controller, string $action): void
|
|
{
|
|
self::register($route, $controller, $action, "POST");
|
|
}
|
|
|
|
/**
|
|
* Register route
|
|
*
|
|
* @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
|
|
{
|
|
// Convert route with parameters into regex
|
|
$routeRegex = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<\1>[a-zA-Z0-9_-]+)', $route);
|
|
$routeRegex = '#^' . $routeRegex . '$#';
|
|
|
|
self::$routes[$method][$routeRegex] = [
|
|
'controller' => $controller,
|
|
'action' => $action,
|
|
'original' => $route,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Dispatch router and run application
|
|
*
|
|
* @return void
|
|
*/
|
|
public static function dispatch(): void
|
|
{
|
|
// Create request
|
|
$request = new Request($_POST + $_FILES);
|
|
|
|
// Dispatch router
|
|
RouteDispatcher::dispatch($request, self::$routes);
|
|
}
|
|
} |