Failed Conditions
Push — master ( f2bb18...5e6761 )
by Adrien
02:12
created

FileAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 17
c 1
b 0
f 0
dl 0
loc 44
ccs 0
cts 23
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 24 4
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Action;
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
use Psr\Http\Server\RequestHandlerInterface;
13
14
class FileAction extends AbstractAction
15
{
16
    /**
17
     * @var ObjectRepository
18
     */
19
    private $fileRepository;
20
21
    public function __construct(ObjectRepository $fileRepository)
22
    {
23
        $this->fileRepository = $fileRepository;
24
    }
25
26
    /**
27
     * Serve a downloaded file from disk
28
     *
29
     * @param ServerRequestInterface $request
30
     * @param RequestHandlerInterface $handler
31
     *
32
     * @return ResponseInterface
33
     */
34
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
35
    {
36
        $id = $request->getAttribute('id');
37
38
        /** @var null|File $file */
39
        $file = $this->fileRepository->find($id);
40
        if (!$file) {
41
            return $this->createError("File $id not found in database");
42
        }
43
44
        $path = $file->getPath();
45
        if (!is_readable($path)) {
46
            return $this->createError("File for $id not found on disk, or not readable");
47
        }
48
49
        $resource = fopen($path, 'r');
50
        if ($resource === false) {
51
            return $this->createError("Cannot open file for $id on disk");
52
        }
53
        $size = filesize($path);
54
        $type = mime_content_type($path);
55
        $response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]);
56
57
        return $response;
58
    }
59
}
60