<?php
namespace core;
class Router
{
private static array $routes;
private static array $route;
private static function upperCamelCase($name): string
{
return str_replace(' ', '', ucwords(str_replace('-', ' ', $name)));
}
private static function removeQueryString($url)
{
if ($url) {
$params = explode('&', $url, 2);
if (strpos($params[0], '=') === false) {
return rtrim($params[0], '/');
}
}
return false;
}
private static function matchRoute($url): bool
{
foreach (self::$routes as $pattern => $route) {
if (preg_match("#{$pattern}#i", $url, $matches)) {
foreach ($matches as $k => $v) {
if (is_string($k)) {
$route[$k] = $v;
}
}
if (!isset($route['action'])) {
$route['action'] = 'index';
}
self::$route['controller'] = self::upperCamelCase($route['controller']);
self::$route['action'] = lcfirst(self::upperCamelCase($route['action']));
return true;
}
}
return false;
}
public static function add($regex, $route = []): void
{
self::$routes[$regex] = $route;
}
public static function dispatch($url): void
{
if (self::matchRoute(self::removeQueryString($url))) {
$controller = 'app\controllers\\' . self::$route['controller'] . 'Controller';
if (class_exists($controller)) {
$cObj = new $controller(self::$route);
$action = self::$route['action'] . 'Action';
if (method_exists($cObj, $action)) {
$cObj->$action();
$cObj->getView();
} elseif ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
echo "<code>Метод {$controller}::{$action} не найден</code>";
} else {
http_response_code(404);
require_once WWW . '/404.html';
die();
}
} elseif ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
echo "<code>Контроллер {$controller} не найден</code>";
} else {
http_response_code(404);
require_once WWW . '/404.html';
die();
}
} else {
http_response_code(404);
require_once WWW . '/404.html';
die();
}
}
}