Passed
Pull Request — master (#5614)
by Angel Fernando Quiroz
14:23 queued 05:18
created

ThemeController::index()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 34
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 34
rs 9.7333
1
<?php
2
3
namespace Chamilo\CoreBundle\Controller;
4
5
use League\Flysystem\FilesystemException;
6
use League\Flysystem\FilesystemOperator;
7
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
8
use Symfony\Component\DependencyInjection\Attribute\Autowire;
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
11
use Symfony\Component\HttpFoundation\StreamedResponse;
12
use Symfony\Component\Routing\Attribute\Route;
13
14
#[Route('/themes')]
15
class ThemeController extends AbstractController
16
{
17
    /**
18
     * @throws FilesystemException
19
     */
20
    #[Route('/{name}/{path}', name: 'theme_asset', requirements: ['path' => '.+'])]
21
    public function index(
22
        string $name,
23
        string $path,
24
        #[Autowire(service: 'oneup_flysystem.themes_filesystem')] FilesystemOperator $filesystem
25
    ): Response {
26
        $themeDir = basename($name);
27
28
        if (!$filesystem->directoryExists($themeDir)) {
29
            throw $this->createNotFoundException("The folder name does not exist.");
30
        }
31
32
        $filePath = $themeDir.DIRECTORY_SEPARATOR.$path;
33
34
        if (!$filesystem->fileExists($filePath)) {
35
            throw $this->createNotFoundException("The requested file does not exist.");
36
        }
37
38
        $response = new StreamedResponse(function () use ($filesystem, $filePath) {
39
            $outputStream = fopen('php://output', 'wb');
40
41
            $fileStream = $filesystem->readStream($filePath);
42
43
            stream_copy_to_stream($fileStream, $outputStream);
44
        });
45
46
        $mimeType = $filesystem->mimeType($filePath);
47
48
        $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, basename($path));
49
50
        $response->headers->set('Content-Disposition', $disposition);
51
        $response->headers->set('Content-Type', $mimeType ?: 'application/octet-stream');
52
53
        return $response;
54
    }
55
}
56