You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.0 KiB

7 years ago
<?php
namespace frontend\urls;
3 years ago
use common\modules\pages\entities\Page;
use common\modules\pages\repositories\read\PageReadRepository;
7 years ago
use yii\base\BaseObject;
3 years ago
use yii\base\InvalidArgumentException;
7 years ago
use yii\caching\Cache;
use yii\helpers\ArrayHelper;
3 years ago
use yii\web\Request;
use yii\web\UrlManager;
7 years ago
use yii\web\UrlNormalizerRedirectException;
use yii\web\UrlRuleInterface;
class PageUrlRule extends BaseObject implements UrlRuleInterface
{
3 years ago
private PageReadRepository $repository;
private Cache $cache;
7 years ago
public function __construct(PageReadRepository $repository, Cache $cache, $config = [])
{
parent::__construct($config);
$this->repository = $repository;
$this->cache = $cache;
}
3 years ago
/**
* @param UrlManager $manager
* @param Request $request
* @return array|false
* @throws UrlNormalizerRedirectException
*/
public function parseRequest($manager, $request): bool|array
7 years ago
{
$path = $request->pathInfo;
$result = $this->cache->getOrSet(['page_route', 'path' => $path], function () use ($path) {
if (!$page = $this->repository->findBySlug($this->getPathSlug($path))) {
return ['id' => null, 'path' => null];
}
return ['id' => $page->id, 'path' => $this->getPagePath($page)];
}, 1000);
if (empty($result['id'])) {
return false;
}
if ($path != $result['path']) {
throw new UrlNormalizerRedirectException(['page/view', 'id' => $result['id']], 301);
}
return ['page/view', ['id' => $result['id']]];
}
3 years ago
/**
* @param UrlManager $manager
* @param string $route
* @param array $params
* @return mixed
*/
public function createUrl($manager, $route, $params): mixed
7 years ago
{
if ($route == 'page/view') {
if (empty($params['id'])) {
3 years ago
throw new InvalidArgumentException('Empty id.');
7 years ago
}
$id = $params['id'];
$url = $this->cache->getOrSet(['page_route', 'id' => $id], function () use ($id) {
if (!$page = $this->repository->find($id)) {
return null;
}
return $this->getPagePath($page);
});
if (!$url) {
return 'error404';
3 years ago
throw new InvalidArgumentException('Undefined id.');
7 years ago
}
unset($params['id']);
if (!empty($params) && ($query = http_build_query($params)) !== '') {
$url .= '?' . $query;
}
return $url;
}
return false;
}
private function getPathSlug($path): string
{
$chunks = explode('/', $path);
return end($chunks);
}
private function getPagePath(Page $page): string
{
$chunks = ArrayHelper::getColumn($page->getParents()->andWhere(['>', 'depth', 0])->all(), 'slug');
$chunks[] = $page->slug;
return implode('/', $chunks);
}
3 years ago
}