repository = $repository; $this->cache = $cache; } public function parseRequest($manager, $request) { if (preg_match('#^' . $this->prefix . '/(.*[a-z])$#is', $request->pathInfo, $matches)) { $path = $matches['1']; $result = $this->cache->getOrSet( [ 'blog_category_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' => ['blog']]) ); if ( empty( $result['id'] ) ) { return false; } if ( $path != $result['path'] ) { throw new UrlNormalizerRedirectException( [ 'blog/post/category', 'id' => $result['id'], ], 301 ); } return [ 'blog/post/category', [ 'id' => $result['id'] ] ]; } return false; } public function createUrl($manager, $route, $params) { if ($route == 'blog/post/category') { if (empty($params['id'])) { throw new InvalidParamException('Empty id.'); } $id = $params['id']; $url = $this->cache->getOrSet(['blog_category_route', 'id' => $id], function () use ($id) { if (!$post = $this->repository->find($id)) { return null; } return $post->slug; //return $this->getPagePath($post); }, null, new TagDependency(['tags' => ['blog']])); if (!$url) { throw new InvalidParamException('Undefined id.'); } $url = $this->prefix . '/' . $url; 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); } }