DownloadMediaHandler::__invoke()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 1
dl 0
loc 19
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Media\Application\Query;
6
7
use Damax\Media\Application\Exception\MediaNotFound;
8
use Damax\Media\Domain\Model\MediaRepository;
9
use Damax\Media\Domain\Storage\Storage;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
12
use Symfony\Component\HttpFoundation\StreamedResponse;
13
14
final class DownloadMediaHandler extends MediaHandler
15
{
16
    private $storage;
17
18
    public function __construct(MediaRepository $repository, Storage $storage)
19
    {
20
        parent::__construct($repository);
21
22
        $this->storage = $storage;
23
    }
24
25
    /**
26
     * @throws MediaNotFound
27
     */
28
    public function __invoke(DownloadMedia $query): Response
29
    {
30
        $media = $this->getMedia($query);
31
32
        $output = fopen('php://output', 'wb');
33
34
        $response = new StreamedResponse(function () use ($media, $output) {
35
            $this->storage->streamTo($media, $output);
36
        });
37
38
        $file = $media->file();
39
40
        $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file->basename());
41
42
        $response->headers->set('Content-Length', $file->info()->fileSize());
43
        $response->headers->set('Content-Type', $file->info()->mimeType());
44
        $response->headers->set('Content-Disposition', $disposition);
45
46
        return $response;
47
    }
48
}
49