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\File; |
9
|
|
|
use Laminas\Diactoros\Response; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
12
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
13
|
|
|
|
14
|
|
|
class FileAction extends AbstractAction |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var ObjectRepository |
18
|
|
|
*/ |
19
|
|
|
private $fileRepository; |
20
|
|
|
|
21
|
|
|
public function __construct(ObjectRepository $fileRepository) |
22
|
|
|
{ |
23
|
|
|
$this->fileRepository = $fileRepository; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Serve a downloaded file from disk |
28
|
|
|
* |
29
|
|
|
* @param ServerRequestInterface $request |
30
|
|
|
* @param RequestHandlerInterface $handler |
31
|
|
|
* |
32
|
|
|
* @return ResponseInterface |
33
|
|
|
*/ |
34
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
35
|
|
|
{ |
36
|
|
|
$id = $request->getAttribute('id'); |
37
|
|
|
|
38
|
|
|
/** @var null|File $file */ |
39
|
|
|
$file = $this->fileRepository->find($id); |
40
|
|
|
if (!$file) { |
41
|
|
|
return $this->createError("File $id not found in database"); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$path = $file->getPath(); |
45
|
|
|
if (!is_readable($path)) { |
46
|
|
|
return $this->createError("File for $id not found on disk, or not readable"); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$resource = fopen($path, 'r'); |
50
|
|
|
if ($resource === false) { |
51
|
|
|
return $this->createError("Cannot open file for $id on disk"); |
52
|
|
|
} |
53
|
|
|
$size = filesize($path); |
54
|
|
|
$type = mime_content_type($path); |
55
|
|
|
$response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]); |
56
|
|
|
|
57
|
|
|
return $response; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|