1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Ecodev\Felix\Handler; |
||
6 | |||
7 | use Doctrine\Persistence\ObjectRepository; |
||
8 | use Ecodev\Felix\Model\Image; |
||
9 | use Ecodev\Felix\Service\ImageResizer; |
||
10 | use Laminas\Diactoros\Response; |
||
11 | use Psr\Http\Message\ResponseInterface; |
||
12 | use Psr\Http\Message\ServerRequestInterface; |
||
13 | |||
14 | final class ImageHandler extends AbstractHandler |
||
15 | { |
||
16 | 2 | public function __construct(private readonly ObjectRepository $imageRepository, private readonly ImageResizer $imageResizer) |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
17 | { |
||
18 | 2 | } |
|
19 | |||
20 | /** |
||
21 | * Serve an image from disk, with optional dynamic resizing. |
||
22 | */ |
||
23 | 2 | public function handle(ServerRequestInterface $request): ResponseInterface |
|
24 | { |
||
25 | 2 | $id = (int) $request->getAttribute('id'); |
|
26 | |||
27 | /** @var null|Image $image */ |
||
28 | 2 | $image = $this->imageRepository->find($id); |
|
29 | 2 | if (!$image) { |
|
30 | return $this->createError("Image $id not found in database"); |
||
31 | } |
||
32 | |||
33 | 2 | $path = $image->getPath(); |
|
34 | 2 | if (!is_readable($path)) { |
|
35 | return $this->createError("Image for image $id not found on disk, or not readable"); |
||
36 | } |
||
37 | |||
38 | 2 | $maxHeight = (int) $request->getAttribute('maxHeight'); |
|
39 | 2 | if ($maxHeight) { |
|
40 | 2 | $accept = $request->getHeaderLine('accept'); |
|
41 | 2 | $useWebp = str_contains($accept, 'image/webp'); |
|
42 | |||
43 | 2 | $path = $this->imageResizer->resize($image, $maxHeight, $useWebp); |
|
44 | } |
||
45 | |||
46 | 2 | $resource = fopen($path, 'rb'); |
|
47 | 2 | if ($resource === false) { |
|
48 | return $this->createError("Cannot open file for image $id on disk"); |
||
49 | } |
||
50 | |||
51 | 2 | $size = filesize($path); |
|
52 | 2 | $type = mime_content_type($path); |
|
53 | |||
54 | // Be sure that browser show SVG instead of downloading |
||
55 | 2 | if ($type === 'image/svg') { |
|
56 | $type = 'image/svg+xml'; |
||
57 | } |
||
58 | |||
59 | 2 | $response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]); |
|
60 | |||
61 | 2 | return $response; |
|
62 | } |
||
63 | } |
||
64 |