|
| 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\TextResponse; |
| 10 | +use Light\Blog\Repository\CategoryRepository; |
| 11 | +use Mezzio\Template\TemplateRendererInterface; |
| 12 | +use Psr\Http\Message\ResponseInterface; |
| 13 | +use Psr\Http\Message\ServerRequestInterface; |
| 14 | +use Psr\Http\Server\RequestHandlerInterface; |
| 15 | + |
| 16 | +use function file_get_contents; |
| 17 | +use function is_file; |
| 18 | +use function realpath; |
| 19 | +use function rtrim; |
| 20 | +use function str_starts_with; |
| 21 | + |
| 22 | +class GetMarkdownArticleHandler implements RequestHandlerInterface |
| 23 | +{ |
| 24 | + public function __construct( |
| 25 | + private readonly TemplateRendererInterface $template, |
| 26 | + private readonly CategoryRepository $categoryRepository, |
| 27 | + private readonly string $articlesPath, |
| 28 | + ) { |
| 29 | + } |
| 30 | + |
| 31 | + public function handle(ServerRequestInterface $request): ResponseInterface |
| 32 | + { |
| 33 | + $categorySlug = (string) $request->getAttribute('categorySlug'); |
| 34 | + $slug = (string) $request->getAttribute('slug'); |
| 35 | + |
| 36 | + $filePath = $this->resolveFilePath($categorySlug, $slug); |
| 37 | + if ($filePath === null) { |
| 38 | + return $this->notFound(); |
| 39 | + } |
| 40 | + |
| 41 | + return new TextResponse( |
| 42 | + (string) file_get_contents($filePath), |
| 43 | + StatusCodeInterface::STATUS_OK, |
| 44 | + ['Content-Type' => 'text/markdown; charset=utf-8'], |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + private function resolveFilePath(string $categorySlug, string $slug): ?string |
| 49 | + { |
| 50 | + if ($categorySlug === '' || $slug === '') { |
| 51 | + return null; |
| 52 | + } |
| 53 | + |
| 54 | + $base = realpath($this->articlesPath); |
| 55 | + if ($base === false) { |
| 56 | + return null; |
| 57 | + } |
| 58 | + $base = rtrim($base, '/'); |
| 59 | + $realPath = realpath($base . '/' . $categorySlug . '/' . $slug . '.md'); |
| 60 | + if ($realPath === false || ! is_file($realPath)) { |
| 61 | + return null; |
| 62 | + } |
| 63 | + |
| 64 | + if (! str_starts_with($realPath, $base . '/')) { |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + return $realPath; |
| 69 | + } |
| 70 | + |
| 71 | + private function notFound(): HtmlResponse |
| 72 | + { |
| 73 | + return new HtmlResponse( |
| 74 | + $this->template->render('error::404', [ |
| 75 | + 'categories' => $this->categoryRepository->getCategories(), |
| 76 | + ]), |
| 77 | + StatusCodeInterface::STATUS_NOT_FOUND, |
| 78 | + ); |
| 79 | + } |
| 80 | +} |
0 commit comments