Skip to content

Commit

Permalink
feat: 支持使用 URL 参数 r 作为路由
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed May 18, 2020
1 parent 22eddf6 commit 7de4f06
Show file tree
Hide file tree
Showing 4 changed files with 399 additions and 113 deletions.
50 changes: 50 additions & 0 deletions lib/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,21 @@ class Request extends Base implements \ArrayAccess, \Countable, \IteratorAggrega
*/
protected $overwriteFormat = true;

/**
* The param name to receive path info for router, when URL rewrite is not enabled
*
* @var string
*/
protected $routerKey = 'r';

/**
* A flag to indicate whether URL rewriting is enabled, since we cannot detected it in index page(path info is
* always empty).
*
* @var bool
*/
protected $defaultUrlRewrite = true;

/**
* @var string
*/
Expand Down Expand Up @@ -968,6 +983,41 @@ public function getReferer()
return $this->getServer('HTTP_REFERER');
}

/**
* @return string
*/
public function getRouterKey()
{
return $this->routerKey;
}

/**
* Whether URL rewriting is enabled
*
* @return bool
*/
public function isUrlRewrite()
{
if ($this->getPathInfo() !== '/') {
return true;
}
return $this->defaultUrlRewrite;
}

/**
* Receive path info for router
*
* @return string
*/
public function getRouterPathInfo()
{
if ($this->isUrlRewrite()) {
return $this->getPathInfo();
} else {
return '/' . ltrim($this[$this->routerKey], '/');
}
}

/**
* Removes extra keys in data
*/
Expand Down
18 changes: 16 additions & 2 deletions lib/Url.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,21 @@ public function __invoke($url = '', $argsOrParams = array(), $params = array())
*/
protected function to($url = '', $argsOrParams = array(), $params = array())
{
return $this->request->getBaseUrl() . '/' . $this->append($url, $argsOrParams, $params);
if ($this->request->isUrlRewrite()) {
return $this->request->getBaseUrl() . '/' . $this->append($url, $argsOrParams, $params);
}

if (strpos($url, '%s') !== false) {
$url = $this->append($url, $argsOrParams);
$argsOrParams = $params;
}

// Add router path info into url
if ($url) {
$argsOrParams = [$this->request->getRouterKey() => $url] + $argsOrParams;
}

return $this->request->getBaseUrl() . '/' . $this->append('', $argsOrParams);
}

/**
Expand Down Expand Up @@ -85,7 +99,7 @@ public function query($url = '', $argsOrParams = array(), $params = array())
public function append($url = '', $argsOrParams = array(), $params = array())
{
if (strpos($url, '%s') !== false) {
$url = vsprintf($url, (array)$argsOrParams);
$url = vsprintf($url, (array) $argsOrParams);
} else {
$params = $argsOrParams;
}
Expand Down
Loading

0 comments on commit 7de4f06

Please sign in to comment.