repository = $repository; $this->cache = $cache; } /** * @param UrlManager $manager * @param Request $request * @return bool|array * @throws UrlNormalizerRedirectException */ public function parseRequest($manager, $request): bool|array { $uri = ltrim(LanguageHelper::processLangInUrl($request->pathInfo), '/'); if (preg_match('#^' . $this->prefix . '([0-9a-z_\-]*)$#is', $uri, $matches)) { $path = $matches['1']; $result = $this->cache->getOrSet(['page_main_route', 'path' => $path], function () use ($path) { if (!$post = $this->repository->findBySlug($this->getPathSlug($path))) { return ['id' => null, 'path' => null]; } return ['id' => $post->id, 'path' => $post->slug]; }, null, new TagDependency(['tags' => ['pages']])); if (empty($result['id'])) { return false; } if ($path != $result['path']) { throw new UrlNormalizerRedirectException(['pages/page/view', 'id' => $result['id']], 301); } return ['pages/page/view', ['id' => $result['id']]]; } return false; } public function createUrl($manager, $route, $params): bool|string { if ($route == 'pages/page/view') { if (empty($params['id'])) { throw new InvalidArgumentException('Empty id.'); } $id = $params['id']; $url = $this->cache->getOrSet(['page_main_route', 'id' => $id], function () use ($id) { if (!$page = $this->repository->find($id)) { return null; } return $page->slug; }, null, new TagDependency(['tags' => ['pages']])); if (!$url) { return '#'; } return LanguageHelper::addLangToUrl($url, $params['language'] ?? null); } return false; } private function getPathSlug($path): string { $chunks = explode('/', $path); return end($chunks); } }