Skip to content

Instantly share code, notes, and snippets.

@yii2-developer
Forked from rommcr/ContentRoute.php
Created December 23, 2015 08:16
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 yii2-developer/b8f157fff49b323d5ce6 to your computer and use it in GitHub Desktop.
Save yii2-developer/b8f157fff49b323d5ce6 to your computer and use it in GitHub Desktop.
<?php
namespace components\routes;
use yii\web\UrlRule;
use \app\models\Content;
use Yii;
/**
* @author Rom <rommcr@gmail.com>
*/
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