Skip to content

Instantly share code, notes, and snippets.

@chdemko
Created June 8, 2012 13:26
Show Gist options
  • Save chdemko/2895605 to your computer and use it in GitHub Desktop.
Save chdemko/2895605 to your computer and use it in GitHub Desktop.
Replacement for parseRoute function
protected function parseRoute($route)
{
// Initialize variables.
$controller = false;
// Sanitize and explode the route.
$route = trim(parse_url($route, PHP_URL_PATH), ' /');
// If the route is empty then simply return the default route. No parsing necessary.
if ($route == '')
{
return $this->default;
}
// Iterate through all of the known route maps looking for a match.
foreach ($this->maps as $pattern => $name)
{
// Reset the route variables each time. Cleanliness is next to buglessness ... or something. :-)
$vars = array();
// Sanitize and explode the pattern.
$pattern = explode('/', trim(parse_url($pattern, PHP_URL_PATH), ' /'));
$regex = array();
$i = 0;
foreach ($pattern as $segment)
{
if ($segment == '*')
{
$regex[] = '.*';
}
elseif ($segment == '\\*')
{
$regex[] = '/';
$regex[] = '\\*';
}
elseif ($segment == ':')
{
$regex[] = '/';
$regex[] = '[^/]*';
}
elseif ($segment[0] == ':')
{
$i++;
$vars[substr($segment, 1)] = $i;
$regex[] = '/';
$regex[] = '([^/]*)';
}
elseif ($segment[0] == '\\' && $segment[1] == ':')
{
$regex[] = '/';
$regex[] = quotemeta(substr($segment, 1));
}
else
{
$regex[] = '/';
$regex[] = quotemeta($segment);
}
}
if ($regex[0] == '/')
{
$regex = array_slice($regex, 1);
}
if (preg_match(chr(1) . '^' . implode($regex) .'$' . chr(1), $route, $matches))
{
// If we have gotten this far then we have a positive match.
$controller = $name;
// Time to set the input variables.
// We are only going to set them if they don't already exist to avoid overwriting things.
foreach ($vars as $k => $i)
{
$this->input->def($k, $matches[$i]);
// Don't forget to do an explicit set on the GET superglobal.
$this->input->get->def($k, $matches[$i]);
}
break;
}
}
// We were unable to find a route match for the request. Panic.
if (!$controller)
{
throw new InvalidArgumentException(sprintf('Unable to handle request for route `%s`.', $route), 404);
}
return $controller;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment