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

FileHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 39
ccs 0
cts 23
cp 0
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A handle() 0 24 4
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