|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Light\App\Handler; |
| 6 | + |
| 7 | +use Fig\Http\Message\StatusCodeInterface; |
| 8 | +use Laminas\Diactoros\Response\HtmlResponse; |
| 9 | +use Laminas\Diactoros\Response\XmlResponse; |
| 10 | +use Light\App\Service\SitemapGenerator; |
| 11 | +use Light\Blog\Entity\Category; |
| 12 | +use Light\Blog\Repository\CategoryRepository; |
| 13 | +use Mezzio\Template\TemplateRendererInterface; |
| 14 | +use Psr\Http\Message\ResponseInterface; |
| 15 | +use Psr\Http\Message\ServerRequestInterface; |
| 16 | +use Psr\Http\Server\RequestHandlerInterface; |
| 17 | +use Throwable; |
| 18 | + |
| 19 | +use function file_get_contents; |
| 20 | +use function filesize; |
| 21 | +use function is_file; |
| 22 | + |
| 23 | +class GetSitemapViewHandler implements RequestHandlerInterface |
| 24 | +{ |
| 25 | + public function __construct( |
| 26 | + private readonly TemplateRendererInterface $template, |
| 27 | + private readonly CategoryRepository $categoryRepository, |
| 28 | + private readonly SitemapGenerator $sitemapGenerator, |
| 29 | + ) { |
| 30 | + } |
| 31 | + |
| 32 | + public function handle(ServerRequestInterface $request): ResponseInterface |
| 33 | + { |
| 34 | + $sitemapFile = $this->sitemapGenerator->getSitemapFile(); |
| 35 | + |
| 36 | + if (! is_file($sitemapFile) || filesize($sitemapFile) === 0) { |
| 37 | + try { |
| 38 | + $this->sitemapGenerator->write(); |
| 39 | + } catch (Throwable) { |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (! is_file($sitemapFile) || filesize($sitemapFile) === 0) { |
| 44 | + return $this->notFound($this->categoryRepository->getCategories()); |
| 45 | + } |
| 46 | + |
| 47 | + return new XmlResponse( |
| 48 | + (string) file_get_contents($sitemapFile), |
| 49 | + StatusCodeInterface::STATUS_OK, |
| 50 | + ['Content-Type' => SitemapGenerator::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 |
| 64 | + ); |
| 65 | + } |
| 66 | +} |
0 commit comments