Failed Conditions
Push — master ( a427b2...509ea4 )
by Adrien
16:44
created

AccountingDocumentHandler::handle()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 31
ccs 0
cts 16
cp 0
rs 9.6666
cc 4
nc 4
nop 1
crap 20
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)
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 16 at column 49
Loading history...
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