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
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
14
|
|
|
|
15
|
|
|
class AccountingDocumentHandler extends AbstractHandler |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var AccountingDocumentRepository |
19
|
|
|
*/ |
20
|
|
|
private $accountingDocumentRepository; |
21
|
|
|
|
22
|
|
|
public function __construct(AccountingDocumentRepository $accountingDocumentRepository) |
23
|
|
|
{ |
24
|
|
|
$this->accountingDocumentRepository = $accountingDocumentRepository; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Serve a downloaded file from disk |
29
|
|
|
*/ |
30
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
31
|
|
|
{ |
32
|
|
|
$id = $request->getAttribute('id'); |
33
|
|
|
|
34
|
|
|
/** @var null|AccountingDocument $accountingDocument */ |
35
|
|
|
$accountingDocument = $this->accountingDocumentRepository->findOneById($id); |
36
|
|
|
if (!$accountingDocument) { |
37
|
|
|
return $this->createError("AccountingDocument $id not found in database"); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$path = $accountingDocument->getPath(); |
41
|
|
|
if (!is_readable($path)) { |
42
|
|
|
return $this->createError("File for accounting document $id not found on disk, or not readable"); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$resource = fopen($path, 'rb'); |
46
|
|
|
if ($resource === false) { |
47
|
|
|
return $this->createError("Cannot open file for accounting document $id on disk"); |
48
|
|
|
} |
49
|
|
|
$size = filesize($path); |
50
|
|
|
$type = mime_content_type($path); |
51
|
|
|
$ext = pathinfo($path, PATHINFO_EXTENSION); |
52
|
|
|
$response = new Response($resource, 200, [ |
53
|
|
|
'content-type' => $type, |
54
|
|
|
'content-length' => $size, |
55
|
|
|
'content-disposition' => 'attachment; filename=' . $id . '.' . $ext, |
56
|
|
|
]); |
57
|
|
|
|
58
|
|
|
return $response; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|