added support for optional route parameters.

This commit is contained in:
Taylor Otwell 2011-07-13 17:28:42 -05:00
parent c3b8524e1b
commit 398a5bb41a
1 changed files with 14 additions and 3 deletions

View File

@ -41,7 +41,7 @@ public static function route($method, $uri)
{ {
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 @@ private static function load_from_directory($uri)
} }
/** /**
* 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);
} }
/** /**