Last active
February 20, 2018 20:17
-
-
Save kieraneglin/ad67e3bcb36f198356e6ae235cfdf9cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Router { | |
private $routes = []; | |
public function get($pattern, $controller_method) { | |
$this->route('get', $pattern, $controller_method); | |
} | |
public function post($pattern, $controller_method) { | |
$this->route('post', $pattern, $controller_method); | |
} | |
public function patch($pattern, $controller_method) { | |
$this->route('patch', $pattern, $controller_method); | |
} | |
public function puts($pattern, $controller_method) { | |
$this->route('puts', $pattern, $controller_method); | |
} | |
public function delete($pattern, $controller_method) { | |
$this->route('delete', $pattern, $controller_method); | |
} | |
public function route($http_method, $pattern, $controller_method) { | |
$pattern = $this->route_to_regex($pattern); | |
$this->routes[$http_method.$pattern] = [ | |
'http_method' => $http_method, | |
'url_pattern' => $pattern, | |
'controller_method' => $controller_method | |
]; | |
} | |
public function execute($request_data) { | |
foreach ($this->routes as $pattern => $actions) { | |
if ($request_data['REQUEST_METHOD'] === strtoupper($actions['http_method'])) { | |
if(preg_match($actions['url_pattern'], $request_data['REQUEST_URI'], $params) === 1) { | |
$callables = $this->call_controller_class($actions['controller_method']); | |
$controller = new $callables['controller']; | |
array_shift($params); | |
$format = array_key_exists('CONTENT_TYPE', $request_data) ? $request_data['CONTENT_TYPE'] : 'text/html'; | |
$params['format'] = explode('/', $format)[1]; | |
$params['method'] = $request_data['REQUEST_METHOD']; | |
$controller->{$callables['action']}($params); | |
break; | |
} | |
} | |
} | |
} | |
private function route_to_regex($path) { | |
$slashes_escaped = str_replace('/', '\/', $path); | |
$route = preg_replace_callback('/({:.+?})/', function($matches) { | |
$param_name = preg_replace("/[^A-Za-z0-9 ]/", '', $matches[0]); | |
return "(?<{$param_name}>.*)"; | |
}, $slashes_escaped); | |
return '/^'.$route.'$/'; | |
} | |
private function call_controller_class($str) { | |
$callables = explode('#', $str); | |
$controller = []; | |
foreach(explode('/', $callables[0]) as $controller_part) { | |
array_push($controller, ucfirst($controller_part)); | |
} | |
$controller = implode('\\', $controller).'Controller'; | |
return ['controller' => $controller, 'action' => $callables[1]]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment