Skip to content

Instantly share code, notes, and snippets.

@andku83
Last active September 27, 2017 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andku83/36ebbfecd6f203b9dda9b233b58fd57f to your computer and use it in GitHub Desktop.
Save andku83/36ebbfecd6f203b9dda9b233b58fd57f to your computer and use it in GitHub Desktop.
<?php
class SearchUrlRule extends Object implements UrlRuleInterface
{
public $route = 'category/view';
public $routePage = 'page/view';
protected static $_listPageSlugs;
protected static $_searchGroups;
/**
* Creates a URL according to the given route and parameters.
* @param \yii\web\UrlManager $manager the URL manager
* @param string $route the route. It should not have slashes at the beginning or the end.
* @param array $params the parameters
* @return string|boolean the created URL, or false if this rule cannot be used for creating this URL.
*/
public function createUrl($manager, $route, $params)
{
if ($route === $this->routePage) {
if (isset($params['slug'])) {
return $params['slug'];
}
if (isset($params['pageSlug'])) {
return $params['pageSlug'];
}
}
if ($route === $this->route) {
$slugParts = [];
if (isset($params['slug'])) {
return $params['slug'];
}
...
if(!empty($params['filterParams'])){
foreach ($params['filterParams'] as $key => $param){
$params[$key] = $param;
}
unset($params['filterParams']);
}
$url = '';
if (!empty($params) && ($query = http_build_query($params)) !== '') {
$url .= '?' . $query;
}
if (empty($slugParts)) {
$slugParts[] = 'list';
}
return implode('/', $slugParts) . $url;
}
return false;
}
/**
* Parses the given request and returns the corresponding route and parameters.
* @param \yii\web\UrlManager $manager the URL manager
* @param \yii\web\Request $request the request component
* @return array|boolean the parsing result. The route and the parameters are returned as an array.
* If false, it means this rule cannot be used to parse this path info.
*/
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
if (preg_match_all('/([\w._-]+)/', $pathInfo, $matches)) {
if ($matches[1][0] == 'list')
return [$this->route, []];
$pages = $this->pages;
if (isset($pages[$matches[1][0]]))
return [$this->routePage, ['slug'=>$matches[1][0]]];
$searchGroups = $this->searchGroups;
$params = [];
foreach ($matches[1] as $match){
foreach ($searchGroups as $paramName => $group){
if (isset($group[$match])) {
$params[$paramName] = $group[$match];
break;
}
}
}
if ($params)
return [$this->route, $params];
}
return false; // данное правило не применимо
}
protected function getPages()
{
...
}
protected static function getSearchGroups()
{
...
return $searchGroups;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment