-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetFeedViewHandler.php
More file actions
66 lines (56 loc) · 1.86 KB
/
Copy pathGetFeedViewHandler.php
File metadata and controls
66 lines (56 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
namespace Light\App\Handler;
use Fig\Http\Message\StatusCodeInterface;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\XmlResponse;
use Light\App\Service\FeedGenerator;
use Light\Blog\Entity\Category;
use Light\Blog\Repository\CategoryRepository;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;
use function file_get_contents;
use function filesize;
use function is_file;
class GetFeedViewHandler implements RequestHandlerInterface
{
public function __construct(
private readonly TemplateRendererInterface $template,
private readonly CategoryRepository $categoryRepository,
private readonly FeedGenerator $feedGenerator,
) {
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$feedFile = $this->feedGenerator->getFeedFile();
if (! is_file($feedFile) || filesize($feedFile) === 0) {
try {
$this->feedGenerator->write();
} catch (Throwable) {
}
}
if (! is_file($feedFile) || filesize($feedFile) === 0) {
return $this->notFound($this->categoryRepository->getCategories());
}
return new XmlResponse(
(string) file_get_contents($feedFile),
StatusCodeInterface::STATUS_OK,
['Content-Type' => FeedGenerator::CONTENT_TYPE]
);
}
/**
* @param Category[] $categories
*/
private function notFound(array $categories): HtmlResponse
{
return new HtmlResponse(
$this->template->render('error::404', [
'categories' => $categories,
]),
StatusCodeInterface::STATUS_NOT_FOUND
);
}
}