Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Core;
- class Router {
- protected $routes = array();
- public function __construct(array $routes = null) {
- if (is_array($routes)) {
- $this->setRoutes($routes);
- }
- }
- public function setRoutes($routes) {
- foreach ($routes as $k => $v) {
- $route = $k;
- $controller = $v['controller'];
- $action = isset($v['action']) ? $v['action'] : null;
- $this->addRoute($route, $controller, $action);
- }
- }
- public function addRoute($route, $controller, $action = null) {
- list($method, $route) = $this->parseRoute($route);
- $pattern = $this->compileRoute($route);
- $this->routes[$pattern] = array($method, $controller, $action);
- }
- protected function parseRoute($route) {
- if ($route[0] == '/') {
- $method = null;
- }
- else {
- $parts = explode(' ',$route);
- $method = $parts[0];
- $route = $parts[1];
- }
- return array($method, $route);
- }
- protected function compileRoute($route) {
- $replacements = array(
- 'num' => '\d+',
- 'id' => '[1-9]\d*',
- 'str' => '\w+',
- 'any' => '.+',
- );
- $parts = preg_split('/\<(.*)\>/', $route, -1, PREG_SPLIT_DELIM_CAPTURE);
- $i = 0;
- $count = count($parts);
- $pattern = '|^';
- for (;;) {
- $pattern .= preg_quote($parts[$i++]);
- if ($i == $count) {
- break;
- }
- $placeholder = $parts[$i++];
- if (!array_key_exists($placeholder, $replacements)) {
- throw new \Exception("Unknown placeholder <$placeholder> in route \"$route\"");
- }
- $pattern .= "({$replacements[$placeholder]})";
- }
- $pattern .= '$|';
- return $pattern;
- }
- public function serve($path) {
- foreach ($this->routes as $pattern => $route) {
- list($method, $controller, $action) = $route;
- if (preg_match($pattern, $path, $matches) &&
- ($method == null || $method == $_SERVER['REQUEST_METHOD'])) {
- $instance = new $controller();
- $action = is_null($action) ? 'index' : $action;
- return call_user_func_array(array($instance, $action), array_slice($matches, 1));
- }
- }
- throw new NotFound();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement