Passed
Push — master ( 1e501a...58b99e )
by Adrien
08:31
created

ImageAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Action;
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
use Psr\Http\Server\RequestHandlerInterface;
14
15
final class ImageAction extends AbstractAction
16
{
17
    /**
18
     * @var ObjectRepository
19
     */
20
    private $imageRepository;
21
22
    /**
23
     * @var ImageResizer
24
     */
25
    private $imageResizer;
26
27 2
    public function __construct(ObjectRepository $imageRepository, ImageResizer $imageService)
28
    {
29 2
        $this->imageRepository = $imageRepository;
30 2
        $this->imageResizer = $imageService;
31 2
    }
32
33
    /**
34
     * Serve an image from disk, with optional dynamic resizing
35
     */
36 2
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
37
    {
38 2
        $id = $request->getAttribute('id');
39
40
        /** @var null|Image $image */
41 2
        $image = $this->imageRepository->find($id);
42 2
        if (!$image) {
43
            return $this->createError("Image $id not found in database");
44
        }
45
46 2
        $path = $image->getPath();
47 2
        if (!is_readable($path)) {
48
            return $this->createError("Image for image $id not found on disk, or not readable");
49
        }
50
51 2
        $maxHeight = (int) $request->getAttribute('maxHeight');
52 2
        if ($maxHeight) {
53 2
            $accept = $request->getHeaderLine('accept');
54 2
            $useWebp = mb_strpos($accept, 'image/webp') !== false;
55
56 2
            $path = $this->imageResizer->resize($image, $maxHeight, $useWebp);
57
        }
58
59 2
        $resource = fopen($path, 'rb');
60 2
        if ($resource === false) {
61
            return $this->createError("Cannot open file for image $id on disk");
62
        }
63
64 2
        $size = filesize($path);
65 2
        $type = mime_content_type($path);
66
67
        // Be sure that browser show SVG instead of downloading
68 2
        if ($type === 'image/svg') {
69
            $type = 'image/svg+xml';
70
        }
71
72 2
        $response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]);
73
74 2
        return $response;
75
    }
76
}
77