AccountingDocumentHandler::handle()   A
last analyzed

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 0
Metric Value
eloc 18
dl 0
loc 31
ccs 0
cts 20
cp 0
rs 9.6666
c 0
b 0
f 0
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)
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 . '"',
0 ignored issues
show
Bug introduced by
Are you sure $ext of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

50
            'content-disposition' => 'inline; filename="' . $id . '.' . /** @scrutinizer ignore-type */ $ext . '"',
Loading history...
51
        ]);
52
53
        return $response;
54
    }
55
}
56