/
vagan
/
Tasks
Обзор
Документация
Войти
/
vagan
/
Tasks
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
core/Router.php
70 строк
2 KB
Vagan
Test task for beejee
25 фев 2021, 00:59
25 фев 2021, 00:59
83b5f6e
Код
Авторство
О чём код?
<?php namespace core; //use core\View; class Router { protected $routes = []; protected $params = []; public function __construct() { $arr = ROUTES; foreach ($arr as $key => $value) { $this->add($key, $value); } } public function add($route, $params) { $preg = preg_replace('/{([a-z]+):([^\}]+)}/', '(?P<\1>\2)', $route); $route = '#^' . $preg . '$#'; $this->routes[$route] = $params; } public function match() { $url = trim(str_replace(DIR, '', $_SERVER['REQUEST_URI']), '/'); foreach ($this->routes as $route => $params) { if (preg_match($route, $url, $matches)) { foreach ($matches as $key => $match) { if (is_string($key)) { if (is_numeric($match)) { $match = (int) $match; } $params[$key] = $match; } } $this->params = $params; return true; } } return false; } public function run() { if ($this->match()) { $path = 'controllers\\' . ucfirst($this->params['controller']) . 'Controller'; if (class_exists($path)) { $action = $this->params['action'] . 'Action'; if (method_exists($path, $action)) { $controller = new $path($this->params); $controller->$action(); } else { View::errorCode(404); } } else { View::errorCode(404); } } else { View::errorCode(404); } } }