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
|
|
|
class ImageAction extends AbstractAction |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var ObjectRepository |
19
|
|
|
*/ |
20
|
|
|
private $imageRepository; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var ImageResizer |
24
|
|
|
*/ |
25
|
|
|
private $imageResizer; |
26
|
|
|
|
27
|
|
|
public function __construct(ObjectRepository $imageRepository, ImageResizer $imageService) |
28
|
|
|
{ |
29
|
|
|
$this->imageRepository = $imageRepository; |
30
|
|
|
$this->imageResizer = $imageService; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Serve an image from disk, with optional dynamic resizing |
35
|
|
|
* |
36
|
|
|
* @param ServerRequestInterface $request |
37
|
|
|
* @param RequestHandlerInterface $handler |
38
|
|
|
* |
39
|
|
|
* @return ResponseInterface |
40
|
|
|
*/ |
41
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
42
|
|
|
{ |
43
|
|
|
$id = $request->getAttribute('id'); |
44
|
|
|
|
45
|
|
|
/** @var null|Image $image */ |
46
|
|
|
$image = $this->imageRepository->find($id); |
47
|
|
|
if (!$image) { |
48
|
|
|
return $this->createError("Image $id not found in database"); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$path = $image->getPath(); |
52
|
|
|
if (!is_readable($path)) { |
53
|
|
|
return $this->createError("Image for image $id not found on disk, or not readable"); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$maxHeight = (int) $request->getAttribute('maxHeight'); |
57
|
|
|
if ($maxHeight) { |
58
|
|
|
$path = $this->imageResizer->resize($image, $maxHeight); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$resource = fopen($path, 'r'); |
62
|
|
|
if ($resource === false) { |
63
|
|
|
return $this->createError("Cannot open file for image $id on disk"); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$size = filesize($path); |
67
|
|
|
$type = mime_content_type($path); |
68
|
|
|
|
69
|
|
|
// Be sure that browser show SVG instead of downloading |
70
|
|
|
if ($type === 'image/svg') { |
71
|
|
|
$type = 'image/svg+xml'; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]); |
75
|
|
|
|
76
|
|
|
return $response; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|