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
|
6 |
|
public function __construct(private readonly ObjectRepository $imageRepository, private readonly ImageResizer $imageResizer) |
17
|
|
|
{ |
18
|
6 |
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Serve an image from disk, with optional dynamic resizing. |
22
|
|
|
*/ |
23
|
6 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
24
|
|
|
{ |
25
|
6 |
|
$id = (int) $request->getAttribute('id'); |
26
|
|
|
|
27
|
|
|
/** @var null|Image $image */ |
28
|
6 |
|
$image = $this->imageRepository->find($id); |
29
|
6 |
|
if (!$image) { |
30
|
1 |
|
return $this->createError("Image $id not found in database"); |
31
|
|
|
} |
32
|
|
|
|
33
|
5 |
|
$path = $image->getPath(); |
34
|
5 |
|
if (!is_readable($path)) { |
35
|
1 |
|
return $this->createError("Image for image $id not found on disk, or not readable"); |
36
|
|
|
} |
37
|
|
|
|
38
|
4 |
|
$isWebp = $image->getMime() === 'image/webp'; |
39
|
4 |
|
$accept = $request->getHeaderLine('accept'); |
40
|
4 |
|
$acceptWebp = str_contains($accept, 'image/webp'); |
41
|
|
|
|
42
|
4 |
|
$maxHeight = (int) $request->getAttribute('maxHeight'); |
43
|
4 |
|
if ($maxHeight) { |
44
|
2 |
|
$path = $this->imageResizer->resize($image, $maxHeight, $acceptWebp); |
45
|
2 |
|
} elseif ($isWebp && !$acceptWebp) { |
46
|
1 |
|
$path = $this->imageResizer->webpToJpg($image); |
47
|
|
|
} |
48
|
|
|
|
49
|
4 |
|
$resource = fopen($path, 'rb'); |
50
|
4 |
|
if ($resource === false) { |
51
|
|
|
return $this->createError("Cannot open file for image $id on disk"); |
52
|
|
|
} |
53
|
|
|
|
54
|
4 |
|
$size = filesize($path); |
55
|
4 |
|
$type = mime_content_type($path); |
56
|
|
|
|
57
|
|
|
// Be sure that browser show SVG instead of downloading |
58
|
4 |
|
if ($type === 'image/svg') { |
59
|
|
|
$type = 'image/svg+xml'; |
60
|
|
|
} |
61
|
|
|
|
62
|
4 |
|
$response = new Response($resource, 200, [ |
63
|
4 |
|
'content-type' => $type, |
64
|
4 |
|
'content-length' => $size, |
65
|
4 |
|
'cache-control' => 'max-age=' . (6 * 60 * 60), // 6 hours cache |
66
|
4 |
|
]); |
67
|
|
|
|
68
|
4 |
|
return $response; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|