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.

99 lines
2.9 KiB

7 years ago
<?php
namespace frontend\urls;
use core\entities\post\PostCategory;
use core\entities\post\PostType;
use core\repositories\post\read\PostCategoryReadRepository;
use yii\base\BaseObject;
3 years ago
use yii\base\InvalidArgumentException;
7 years ago
use yii\caching\Cache;
3 years ago
use yii\web\Request;
use yii\web\UrlManager;
7 years ago
use yii\web\UrlNormalizerRedirectException;
use yii\web\UrlRuleInterface;
class PostCategoryUrlRule extends BaseObject implements UrlRuleInterface
{
3 years ago
private PostCategoryReadRepository $repository;
private Cache $cache;
7 years ago
public function __construct(PostCategoryReadRepository $repository, Cache $cache, $config = [])
{
parent::__construct($config);
$this->repository = $repository;
$this->cache = $cache;
}
3 years ago
/**
* @param UrlManager $manager
* @param Request $request
* @return bool|array
* @throws UrlNormalizerRedirectException
*/
public function parseRequest($manager, $request): bool|array
7 years ago
{
$path = $request->pathInfo;
$result = $this->cache->getOrSet(['category_route', 'path' => $path], function () use ($path) {
if (!$post = $this->repository->findBySlug($this->getPathSlug($path))) {
return ['id' => null, 'path' => null];
}
return ['id' => $post->id, 'tid' => $post->type_id, 'path' => $this->getPagePath($post)];
}, 1);
if (empty($result['id'])) {
return false;
}
if ($path != $result['path']) {
throw new UrlNormalizerRedirectException(['post/category', 'id' => $result['id'], 'tid' => $result['tid']], 301);
}
return ['post/category', ['id' => $result['id'], 'tid' => $result['tid']]];
}
public function createUrl($manager, $route, $params)
{
if ($route == 'post/category') {
if (empty($params['id'])) {
3 years ago
throw new InvalidArgumentException('Empty id.');
7 years ago
}
$id = $params['id'];
$url = $this->cache->getOrSet(['category_route', 'id' => $id], function () use ($id) {
if (!$post = $this->repository->find($id)) {
return null;
}
return $this->getPagePath($post);
});
if (!$url) {
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(PostCategory $category): string
{
$type = PostType::findOne($category->type_id);
$chunks = ['post', 'category' , $type->name];
$chunks[] = $category->slug;
return implode('/', $chunks);
}
3 years ago
}