Passed
Push — master ( 89f24e...8c4dad )
by Sylvain
08:05
created

FileHandler::handle()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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