Skip to content

Instantly share code, notes, and snippets.

@wilcorrea
Last active August 7, 2020 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilcorrea/43c53a2cd460024365f02dabce4d36a0 to your computer and use it in GitHub Desktop.
Save wilcorrea/43c53a2cd460024365f02dabce4d36a0 to your computer and use it in GitHub Desktop.
<?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