1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Application\Handler; |
6
|
|
|
|
7
|
|
|
use Application\Model\AccountingDocument; |
8
|
|
|
use Application\Repository\AccountingDocumentRepository; |
9
|
|
|
use Ecodev\Felix\Handler\AbstractHandler; |
10
|
|
|
use Laminas\Diactoros\Response; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
13
|
|
|
|
14
|
|
|
class AccountingDocumentHandler extends AbstractHandler |
15
|
|
|
{ |
16
|
|
|
public function __construct(private readonly AccountingDocumentRepository $accountingDocumentRepository) |
17
|
|
|
{ |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Serve a downloaded file from disk. |
22
|
|
|
*/ |
23
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
24
|
|
|
{ |
25
|
|
|
$id = $request->getAttribute('id'); |
26
|
|
|
|
27
|
|
|
/** @var null|AccountingDocument $accountingDocument */ |
28
|
|
|
$accountingDocument = $this->accountingDocumentRepository->findOneById($id); |
29
|
|
|
if (!$accountingDocument) { |
30
|
|
|
return $this->createError("AccountingDocument $id not found in database"); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$path = $accountingDocument->getPath(); |
34
|
|
|
if (!is_readable($path)) { |
35
|
|
|
return $this->createError("File for accounting document $id not found on disk, or not readable"); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$resource = fopen($path, 'rb'); |
39
|
|
|
if ($resource === false) { |
40
|
|
|
return $this->createError("Cannot open file for accounting document $id on disk"); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$size = filesize($path); |
44
|
|
|
$type = mime_content_type($path); |
45
|
|
|
$ext = pathinfo($path, PATHINFO_EXTENSION); |
46
|
|
|
|
47
|
|
|
$response = new Response($resource, 200, [ |
48
|
|
|
'content-type' => $type, |
49
|
|
|
'content-length' => $size, |
50
|
|
|
'content-disposition' => 'inline; filename="' . $id . '.' . $ext . '"', |
|
|
|
|
51
|
|
|
]); |
52
|
|
|
|
53
|
|
|
return $response; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|