<?php

/**
 * Description of Router
 *
 * @author home
 */

namespace Core;

class Router
{

    public $routes = [];
    public $params = [];

    public function addRoute(string $route, string $controller, string $action)
    {
        //экранируем слеши внутри
        $route = preg_replace('/\//', '\\/', $route);
        
        //вычленяем параметры из строки запроса в фигурных скобках
        $route = preg_replace('/\{([\w\d-]+)\}/', '(?P<\1>[\w\d-]+)', $route);

        //оформляем необходимые для регулярки элементы
        $route = '/^' . $route . '$/';

        $this->routes[] = ['route' => $route, 'controller' => $controller, 'action' => $action];
    }

    public function matchUri()
    {
        $uri = $_SERVER['QUERY_STRING'];

        foreach ($this->routes as $route) {
            if (preg_match($route['route'], $uri, $matches)) {
                
                $this->params['controller'] = $route['controller'];
                $this->params['action'] = $route['action'];
                
                //цикл необходим, т.к. в массив совпаденией попадают элементы как и с цифровы индексом, так и с ассоциативным
                foreach ($matches as $param => $value) {
                    if (is_string($param)) $this->params[$param] = $value;
                }
                
                return $this->params;
            }
        }
    }

}
