class Route
{
/**
* @var array
*/
protected static array $routes = [];
/**
* @var array
*/
protected static array $route = [];
/**
* @param string $url
* @param array $route
* @return void
*/
public static function add(string $url, array $route = []): void
{
self::$routes[$url] = $route;
}
/**
* @param string $url
* @return array
*/
public static function getRoute(string $url): array
{
foreach (self::$routes as $item => $value) {
if (preg_match("#$item#", $url, $match_array)) {
foreach ($match_array as $key => $val) {
if (is_string($key)) {
self::$route[$key] = $val;
}
}
}
if (!isset(self::$route['controller'])) {
self::$route['controller'] = 'Main';
self::$route['action'] = 'index';
}
if (!isset(self::$route['action'])) {
self::$route['action'] = 'index';
}
}
return self::$route;
}
/**
* @param string $url
* @return void
*/
public static function dispatch(string $url): void
{
try {
self::getRoute($url);
$controller = "App\\Controllers\\" . ucfirst(self::$route['controller']) . 'Controller';
$obj = new $controller(self::$route);
$action = self::$route['action'];
if (isset(self::$route['params'])) {
$id = explode('=', self::$route['params']);
$id = $id[1];
$obj->$action($id);
} else {
$obj->$action();
}
} catch (\Error $e) {
Logger::log($e->getMessage());
include ROOT.'/public/404.html';
}
}
}
//Добавление роутов в массив:
Route::add('^/?$');
Route::add('^/(?P<controller>[a-z-]+)/?$');
Route::add('^/(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)/?$');
Route::add(('^/(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)[?](?P<params>[a-z-=0-9]+)/?$'));
define('URL', $_SERVER['REQUEST_URI']);
Route::dispatch(URL);