Last active
August 7, 2020 19:20
-
-
Save wilcorrea/43c53a2cd460024365f02dabce4d36a0 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 | |
namespace Hero; | |
class Router | |
{ | |
private $routes = []; | |
public function on($method, $path, $callback) | |
{ | |
$method = strtolower($method); | |
if (!isset($this->routes[$method])) { | |
$this->routes[$method] = []; | |
} | |
$uri = substr($path, 0, 1) !== '/' ? '/' . $path : $path; | |
$pattern = str_replace('/', '\/', $uri); | |
$route = '/^' . $pattern . '$/'; | |
$this->routes[$method][$route] = $callback; | |
return $this; | |
} | |
function run($method, $uri) | |
{ | |
$method = strtolower($method); | |
if (!isset($this->routes[$method])) { | |
return null; | |
} | |
foreach ($this->routes[$method] as $route => $callback) { | |
if (preg_match($route, $uri, $parameters)) { | |
array_shift($parameters); | |
return call_user_func_array($callback, $parameters); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment