66
77use Fig \Http \Message \StatusCodeInterface ;
88use Laminas \Diactoros \Response \HtmlResponse ;
9+ use Light \Blog \Entity \Category ;
910use Light \Blog \Repository \CategoryRepository ;
1011use Mezzio \Template \TemplateRendererInterface ;
1112use Psr \Http \Message \ResponseInterface ;
1213use Psr \Http \Message \ServerRequestInterface ;
1314use Psr \Http \Server \RequestHandlerInterface ;
15+ use Throwable ;
1416
1517class GetCategoryResourceHandler implements RequestHandlerInterface
1618{
@@ -23,21 +25,40 @@ public function __construct(
2325 public function handle (ServerRequestInterface $ request ): ResponseInterface
2426 {
2527 $ categorySlug = $ request ->getAttribute ('slug ' );
28+ $ categories = $ this ->categoryRepository ->getCategories ();
2629 $ category = $ this ->categoryRepository ->getCategoryResource ($ categorySlug );
27- $ meta = $ category ;
28-
29- if (! $ category ) {
30- return new HtmlResponse ('Category not found ' , StatusCodeInterface::STATUS_NOT_FOUND );
30+ if ($ category === null ) {
31+ return $ this ->notFound ($ categories );
3132 }
32- $ categories = $ this -> categoryRepository -> getCategories () ;
33+ $ meta = $ category ;
3334 $ categoryArticles = $ this ->categoryRepository ->getCategoryPost ($ category );
35+
36+ try {
37+ $ html = $ this ->template ->render (
38+ 'page::category-resource ' ,
39+ [
40+ 'categories ' => $ categories ,
41+ 'category ' => $ category ,
42+ 'meta ' => $ meta ,
43+ 'categoryArticles ' => $ categoryArticles ,
44+ ]
45+ );
46+ } catch (Throwable $ e ) {
47+ return $ this ->notFound ($ categories );
48+ }
49+ return new HtmlResponse ($ html );
50+ }
51+
52+ /**
53+ * @param Category[] $categories
54+ */
55+ private function notFound (array $ categories ): HtmlResponse
56+ {
3457 return new HtmlResponse (
35- $ this ->template ->render ('page::category-resource ' , [
36- 'categories ' => $ categories ,
37- 'category ' => $ category ,
38- 'meta ' => $ meta ,
39- 'categoryArticles ' => $ categoryArticles ,
40- ])
58+ $ this ->template ->render ('error::404 ' , [
59+ 'categories ' => $ categories ,
60+ ]),
61+ StatusCodeInterface::STATUS_NOT_FOUND
4162 );
4263 }
4364}
0 commit comments