|
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
|
4 |
|
public function __construct(private readonly ObjectRepository $imageRepository, private readonly ImageResizer $imageResizer) |
|
17
|
|
|
{ |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Serve an image from disk, with optional dynamic resizing. |
|
22
|
|
|
*/ |
|
23
|
4 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
24
|
|
|
{ |
|
25
|
4 |
|
$id = (int) $request->getAttribute('id'); |
|
26
|
|
|
|
|
27
|
|
|
/** @var null|Image $image */ |
|
28
|
4 |
|
$image = $this->imageRepository->find($id); |
|
29
|
4 |
|
if (!$image) { |
|
30
|
1 |
|
return $this->createError("Image $id not found in database"); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
3 |
|
$path = $image->getPath(); |
|
34
|
3 |
|
if (!is_readable($path)) { |
|
35
|
1 |
|
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, [ |
|
60
|
|
|
'content-type' => $type, |
|
61
|
|
|
'content-length' => $size, |
|
62
|
|
|
'cache-control' => 'max-age=' . (6 * 60 * 60), // 6 hours cache |
|
63
|
|
|
]); |
|
64
|
|
|
|
|
65
|
2 |
|
return $response; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|