44
55namespace Light \App \Handler ;
66
7+ use Fig \Http \Message \StatusCodeInterface ;
8+ use Laminas \Diactoros \Response \HtmlResponse ;
79use Laminas \Diactoros \Response \XmlResponse ;
810use Light \App \Service \FeedGenerator ;
11+ use Light \Blog \Entity \Category ;
12+ use Light \Blog \Repository \CategoryRepository ;
13+ use Mezzio \Template \TemplateRendererInterface ;
914use Psr \Http \Message \ResponseInterface ;
1015use Psr \Http \Message \ServerRequestInterface ;
1116use Psr \Http \Server \RequestHandlerInterface ;
17+ use Throwable ;
1218
1319use function file_get_contents ;
1420use function filesize ;
1723class GetFeedViewHandler implements RequestHandlerInterface
1824{
1925 public function __construct (
26+ private readonly TemplateRendererInterface $ template ,
27+ private readonly CategoryRepository $ categoryRepository ,
2028 private readonly FeedGenerator $ feedGenerator ,
2129 ) {
2230 }
@@ -26,13 +34,33 @@ public function handle(ServerRequestInterface $request): ResponseInterface
2634 $ feedFile = $ this ->feedGenerator ->getFeedFile ();
2735
2836 if (! is_file ($ feedFile ) || filesize ($ feedFile ) === 0 ) {
29- $ this ->feedGenerator ->write ();
37+ try {
38+ $ this ->feedGenerator ->write ();
39+ } catch (Throwable ) {
40+ }
41+ }
42+
43+ if (! is_file ($ feedFile ) || filesize ($ feedFile ) === 0 ) {
44+ return $ this ->notFound ($ this ->categoryRepository ->getCategories ());
3045 }
3146
3247 return new XmlResponse (
3348 (string ) file_get_contents ($ feedFile ),
34- 200 ,
35- ['content-type ' => FeedGenerator::CONTENT_TYPE ]
49+ StatusCodeInterface::STATUS_OK ,
50+ ['Content-Type ' => FeedGenerator::CONTENT_TYPE ]
51+ );
52+ }
53+
54+ /**
55+ * @param Category[] $categories
56+ */
57+ private function notFound (array $ categories ): HtmlResponse
58+ {
59+ return new HtmlResponse (
60+ $ this ->template ->render ('error::404 ' , [
61+ 'categories ' => $ categories ,
62+ ]),
63+ StatusCodeInterface::STATUS_NOT_FOUND
3664 );
3765 }
3866}
0 commit comments