Skip to content

Instantly share code, notes, and snippets.

@teresko
Created April 18, 2015 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teresko/a8fde97efe4f450aa1af to your computer and use it in GitHub Desktop.
Save teresko/a8fde97efe4f450aa1af to your computer and use it in GitHub Desktop.
<?php
class Router
{
private $uri;
private $cache = [];
public function setUri($uri)
{
$this->uri = $uri;
}
public function parse($notation)
{
if (! array_key_exists($notation, $this->cache)) {
$this->cache[$notation] = $this->transform($notation);
}
return $this->apply($this->uri, $this->cache[$notation]);
}
private function transform($notation)
{
$map = [
'{' => '(?P<',
'}' => '>[^/\\\\.,;?\n]+)',
];
$pattern = strtr($notation, $map);
$pattern = "#^{$pattern}$#i";
return $pattern;
}
private function apply($uri, $expression)
{
$matches = [];
if (preg_match($expression, $uri, $matches)) {
return $this->clean($matches);
}
return false;
}
private function clean($matches)
{
$list = [];
foreach ($matches as $key => $value) {
if (is_numeric($key) === false && $value !== '') {
$list[$key] = $value;
}
}
return $list;
}
}
$router = new Router;
$router->setUri('user/3');
var_dump($router->parse('user/{id}'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment