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.

97 lines
2.8 KiB

7 years ago
<?php
namespace frontend\urls;
use core\entities\post\PostType;
use core\repositories\post\read\PostTypeReadRepository;
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 PostMainUrlRule extends BaseObject implements UrlRuleInterface
{
3 years ago
public string $prefix = 'post';
7 years ago
3 years ago
private PostTypeReadRepository $repository;
private Cache $cache;
7 years ago
public function __construct(PostTypeReadRepository $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;
3 years ago
$result = $this->cache->getOrSet( [ 'post_main_route', 'path' => $path ], function () use ( $path ) {
if ( ! $type = $this->repository->findByName( $this->getPathName( $path ) ) ) {
return [ 'tid' => null, 'path' => null ];
}
7 years ago
3 years ago
return [ 'tid' => $type->id, 'path' => $this->getPagePath( $type ) ];
}, 1000 );
7 years ago
3 years ago
if ( empty( $result['tid'] ) ) {
return false;
}
7 years ago
3 years ago
if ( $path != $result['path'] ) {
throw new UrlNormalizerRedirectException( [ 'post/index', 'tid' => $result['tid'] ], 301 );
}
7 years ago
3 years ago
return [ 'post/index', [ 'tid' => $result['tid'] ] ];
7 years ago
}
public function createUrl($manager, $route, $params)
{
if ($route == 'post/index') {
if (empty($params['tid'])) {
3 years ago
throw new InvalidArgumentException('Empty type.');
7 years ago
}
$tid = $params['tid'];
$url = $this->cache->getOrSet(['post_main_route', 'tid' => $tid], function () use ($tid) {
if (!$type = $this->repository->find($tid)) {
return null;
}
return $this->getPagePath($type);
});
if (!$url) {
3 years ago
throw new InvalidArgumentException('Undefined id.');
7 years ago
}
unset($params['tid']);
if (!empty($params) && ($query = http_build_query($params)) !== '') {
$url .= '?' . $query;
}
return $url;
}
return false;
}
private function getPathName($path): string
{
$chunks = explode('/', $path);
return end($chunks);
}
private function getPagePath(PostType $type): string
{
$chunks = ['post', $type->name];
return implode('/', $chunks);
}
}