ImageHandler::handle()   B
last analyzed

Complexity

Conditions 8
Paths 11

Size

Total Lines 46
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 8.021

Importance

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