Маршрутизатор и твердый принцип

Я хотел бы знать, соблюдает ли моя система маршрутизации твердый принцип?

Система проста: класс Router содержит маршруты и возвращает правильный маршрут, а класс Route представляет маршрут, содержит путь и вызываемое действие. Маршрутизатор принимает класс Request в качестве параметра в своем конструкторе, чтобы попытаться соблюдать твердый принцип.

Хотелось бы знать, что хорошо, а что нет.

class Router
{
    private $request;
    private $routes = [];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }
  
    public function get(string $path, string $action)
    {
        return $this->addRoute($path, $action, 'GET');
    }

    private function addRoute(string $path, string $action, string $method)
    {
        $route = new Route($path, $action);
        $this->routes[$method][] = $route;
        return $route;
    }

    public function run()
    {
        if(!isset($this->routes[$this->request->getMETHOD()])) {
            throw new RouterException('REQUEST_METHOD does not exist');
        }
        foreach ($this->routes[$this->request->getMETHOD()] as $route) {
            if ($route->match($this->request->getUri())) {
                return $route->call();
            }
        }
        throw new RouterException("La page demandée est introuvable.");
    }
}
class Route
{
    private $path;   
    private $action; 
    private $matches; 
    private $parameters = [];

    public function __construct(string $path, string $action)
    {
        $this->path = trim($path, "https://codereview.stackexchange.com/");
        $this->action = $action;
    }

    public function where(string $param, string $regex)
    {
        $this->parameters[$param] = str_replace('(', '(?:', $regex);
        return $this; 
    }

    public function match(string $requestUri)
    {
        $requestUri = trim($requestUri, "https://codereview.stackexchange.com/");
        $path = preg_replace_callback('#:([w]+)#', [$this, 'paramMatch'], $this->path); 
        $regex = "#^$path$#";
        if (preg_match($regex, $requestUri, $matches)) {
            array_shift($matches);
            $this->matches = $matches;
            return true;
        } else {
            return false;
        }
    }

    private function paramMatch(array $match)
    {
        if (isset($this->parameters[$match[1]])) {
            return '(' . $this->parameters[$match[1]] . ')';
        }
        return '([^/]+)';
    }

    public function call()
    {
        $parameters = explode('@', $this->action);
        $controller = "Src\Controller\" . $parameters[0];
        $controller = new $controller();
        $method = $parameters[1];
        return call_user_func_array([$controller, $method], $this->matches);
    }
}

0

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *