Completed
Pull Request — master (#19)
by
unknown
01:25
created

createStreamedResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * another great project.
7
 * You can find more information about us on https://bitbag.io and write us
8
 * an email on [email protected].
9
 */
10
11
declare(strict_types=1);
12
13
namespace BitBag\SyliusShippingExportPlugin\Controller;
14
15
use BitBag\SyliusShippingExportPlugin\Repository\ShippingExportRepositoryInterface;
16
use Symfony\Component\Filesystem\Filesystem;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
20
use Symfony\Component\HttpFoundation\StreamedResponse;
21
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
22
use Webmozart\Assert\Assert;
23
24
final class ShippingExportDownloadLabelAction
25
{
26
    /** @var Filesystem */
27
    private $filesystem;
28
29
    /** @var ShippingExportRepositoryInterface */
30
    private $repository;
31
32
    public function __construct(Filesystem $filesystem, ShippingExportRepositoryInterface $repository)
33
    {
34
        $this->filesystem = $filesystem;
35
        $this->repository = $repository;
36
    }
37
38
    public function __invoke(Request $request): Response
39
    {
40
        $shippingExport = $this->repository->find($request->get('id'));
41
        Assert::notNull($shippingExport);
42
43
        $labelPath = $shippingExport->getLabelPath();
44
        Assert::notNull($labelPath);
45
46
        if (false === $this->filesystem->exists($labelPath)) {
47
            throw new NotFoundHttpException();
48
        }
49
50
        $filePathParts = explode(\DIRECTORY_SEPARATOR, $labelPath);
51
        $labelName = end($filePathParts);
52
53
        return $this->createStreamedResponse($labelPath, $labelName);
54
    }
55
56
    private function createStreamedResponse(string $filePath, string $fileName): StreamedResponse
57
    {
58
        $response = new StreamedResponse(function () use ($filePath): void {
59
            $outputStream = fopen('php://output', 'wb');
60
            Assert::resource($outputStream);
61
            $fileStream = fopen($filePath, 'rb');
62
            Assert::resource($fileStream);
63
            stream_copy_to_stream($fileStream, $outputStream);
64
        });
65
66
        $disposition = $response->headers->makeDisposition(
67
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
68
            $fileName
69
        );
70
        $response->headers->set('Content-Disposition', $disposition);
71
72
        return $response;
73
    }
74
}
75