Commit 398a5bb4 authored by Taylor Otwell's avatar Taylor Otwell

added support for optional route parameters.

parent c3b8524e
...@@ -41,7 +41,7 @@ class Router { ...@@ -41,7 +41,7 @@ class Router {
{ {
foreach (explode(', ', $keys) as $key) foreach (explode(', ', $keys) as $key)
{ {
if (preg_match('#^'.$key = static::translate_wildcards($key).'$#', $uri)) if (preg_match('#^'.static::translate_wildcards($key).'$#', $uri))
{ {
return Request::$route = new Route($keys, $callback, static::parameters($uri, $key)); return Request::$route = new Route($keys, $callback, static::parameters($uri, $key));
} }
...@@ -77,14 +77,25 @@ class Router { ...@@ -77,14 +77,25 @@ class Router {
} }
/** /**
* Translate route URI wildcards to regular expressions. * Translate route URI wildcards into actual regular expressions.
* *
* @param string $key * @param string $key
* @return string * @return string
*/ */
private static function translate_wildcards($key) private static function translate_wildcards($key)
{ {
return str_replace(':num', '[0-9]+', str_replace(':any', '[a-zA-Z0-9\-_]+', $key)); $replacements = 0;
// For optional parameters, first translate the wildcards to their regex equivalent, sans the ")?" ending.
$key = str_replace(array('/(:num?)', '/(:any?)'), array('(?:/([0-9]+)', '(?:/([a-zA-Z0-9\-_]+)'), $key, $replacements);
// Now, to properly close the regular expression, we need to append a ")?" for each optional segment in the route.
if ($replacements > 0)
{
$key .= implode('', array_fill(0, $replacements, ')?'));
}
return str_replace(array(':num', ':any'), array('[0-9]+', '[a-zA-Z0-9\-_]+'), $key);
} }
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment