FileHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 1
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Handler;
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
13
final class FileHandler extends AbstractHandler
14
{
15
    public function __construct(private readonly ObjectRepository $fileRepository)
16
    {
17
    }
18
19
    /**
20
     * Serve a downloaded file from disk.
21
     */
22
    public function handle(ServerRequestInterface $request): ResponseInterface
23
    {
24
        $id = (int) $request->getAttribute('id');
25
26
        /** @var null|File $file */
27
        $file = $this->fileRepository->find($id);
28
        if (!$file) {
29
            return $this->createError("File $id not found in database");
30
        }
31
32
        $path = $file->getPath();
33
        if (!is_readable($path)) {
34
            return $this->createError("File for $id not found on disk, or not readable");
35
        }
36
37
        $resource = fopen($path, 'rb');
38
        if ($resource === false) {
39
            return $this->createError("Cannot open file for $id on disk");
40
        }
41
        $size = filesize($path);
42
        $type = mime_content_type($path);
43
        $response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]);
44
45
        return $response;
46
    }
47
}
48