根据路由获取URI,为get方法相反操作
string Core_Route::uri( [ array $params = null ] )
参数列表
参数 类型 描述 默认值 $params
array
URI parameters null
string
public static function uri(array $params = null)
{
if (!isset(Route::$regex[Core::$project]))
{
# 构造路由正则
Route::init_regex();
}
$current_route = Core::config('route.'.Route::$current_route);
if (!isset($current_route['default']) || !is_array($current_route['default']))$current_route['default'] = array();
if (null===$params)
{
// 使用默认参数
$params = $current_route['default'];
}
else
{
// 覆盖默认参数
$params += $current_route['default'];
}
// 获取URI
$uri = $current_route['uri'];
if (strpos($uri, '<') === false && strpos($uri, '(') === false)
{
// This is a static route, no need to replace anything
return $uri;
}
$provided_optional = false;
while (preg_match('#\([^()]++\)#', $uri, $match))
{
// Search for the matched value
$search = $match[0];
// Remove the parenthesis from the match as the replace
$replace = substr($match[0], 1, -1);
while (preg_match('#' . Route::REGEX_KEY . '#', $replace, $match))
{
list ($key, $param) = $match;
if (isset($params[$param]) && ($params[$param]!==Route::arr_get($current_route['default'],$param)))
{
$provided_optional = true;
// Replace the key with the parameter value
$replace = str_replace($key, $params[$param], $replace);
}
elseif ($provided_optional)
{
// Look for a default
if (isset($current_route['default'][$param]))
{
$replace = str_replace($key, $current_route['default'][$param], $replace);
}
else
{
// Ungrouped parameters are required
throw new Exception(__('Required route parameter not passed: :param', array(':param' => $param)));
}
}
else
{
// This group has missing parameters
$replace = '';
break;
}
}
// Replace the group in the URI
$uri = str_replace($search, $replace, $uri);
}
while (preg_match('#' . Route::REGEX_KEY . '#', $uri, $match))
{
list($key, $param) = $match;
if ( !isset($params[$param]) )
{
if (isset($current_route['default'][$param]))
{
$params[$param] = $current_route['default'][$param];
}
else
{
// Ungrouped parameters are required
throw new Exception(__('Required route parameter not passed: :param', array(':param' => $param)));
}
}
$uri = str_replace($key, $params[$param], $uri);
}
// Trim all extra slashes from the URI
$uri = preg_replace('#//+#', '/', rtrim($uri, '/'));
if (isset($current_route['defaults']['host']))
{
if (false===strpos($current_route['defaults']['host'], '://'))
{
$host = HttpIO::PROTOCOL.$host;
}
$uri = rtrim($host, '/') . '/' . $uri;
}
return $uri;
}