-
-
Save yii2-developer/b8f157fff49b323d5ce6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace components\routes; | |
use yii\web\UrlRule; | |
use \app\models\Content; | |
use Yii; | |
/** | |
* @author Rom <[email protected]> | |
*/ | |
class ContentRoute extends UrlRule | |
{ | |
static $content; | |
public function init() | |
{ | |
parent::init(); | |
self::$content = Content::find()->indexBy('alias')->all(); | |
} | |
public function parseRequest($manager, $request) | |
{ | |
if ($this->mode === self::CREATION_ONLY) { | |
return false; | |
} | |
if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb,true)) { | |
return false; | |
} | |
$pathInfo = $request->getPathInfo(); | |
$suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix); | |
if ($suffix !== '' && $pathInfo !== '') { | |
$n = strlen($suffix); | |
if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) { | |
$pathInfo = substr($pathInfo, 0, -$n); | |
if ($pathInfo === '') { | |
// suffix alone is not allowed | |
return false; | |
} | |
} else { | |
return false; | |
} | |
} | |
if ($this->host !== null) { | |
$pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo); | |
} | |
if (!preg_match($this->pattern, $pathInfo, $matches)) { | |
return false; | |
} | |
foreach ($this->defaults as $name => $value) { | |
if (!isset($matches[$name]) || $matches[$name] === '') { | |
$matches[$name] = $value; | |
} | |
} | |
$content = Content::findOne(['path' => $matches['route']]); | |
if (!$content) { | |
return false; | |
} | |
return [$this->route, | |
['alias' => $content->alias]]; | |
} | |
public function createUrl($manager, $route, $params) | |
{ | |
if (!array_key_exists('alias', $params)) { | |
return false; | |
} | |
$data = array_key_exists($params['alias'], self::$content) ? self::$content[$params['alias']] : false; | |
if ($data) { | |
return $data['path'] . '/'; | |
} | |
return parent::createUrl($manager, $route, $params); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment