1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Application\Action; |
6
|
|
|
|
7
|
|
|
use Application\Model\Image; |
8
|
|
|
use Application\Repository\ImageRepository; |
9
|
|
|
use Application\Service\ImageResizer; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
12
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
13
|
|
|
use Zend\Diactoros\Response; |
14
|
|
|
|
15
|
|
|
class ImageAction extends AbstractAction |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var ImageRepository |
19
|
|
|
*/ |
20
|
|
|
private $imageRepository; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var ImageResizer |
24
|
|
|
*/ |
25
|
|
|
private $imageService; |
26
|
|
|
|
27
|
|
|
public function __construct(ImageRepository $imageRepository, ImageResizer $imageService) |
28
|
|
|
{ |
29
|
|
|
$this->imageRepository = $imageRepository; |
30
|
|
|
$this->imageService = $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 Image $image */ |
46
|
|
|
$image = $this->imageRepository->findOneById($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->imageService->resize($image, $maxHeight); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$resource = fopen($path, 'r'); |
62
|
|
|
$type = mime_content_type($path); |
63
|
|
|
$response = new Response($resource, 200, ['content-type' => $type]); |
|
|
|
|
64
|
|
|
|
65
|
|
|
return $response; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|