Passed
Push — master ( a21940...8fc5ed )
by Peter
02:25
created

Assets::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Http\Controllers\Website;
6
7
use AbterPhp\Framework\Assets\AssetManager;
8
use AbterPhp\Framework\Http\Controllers\ControllerAbstract;
9
use AbterPhp\Framework\Session\FlashService;
10
use Opulence\Http\Responses\Response;
11
use Opulence\Http\Responses\ResponseHeaders;
12
13
class Assets extends ControllerAbstract
14
{
15
    /** @var AssetManager */
16
    protected $assetManager;
17
18
    /**
19
     * Assets constructor.
20
     *
21
     * @param FlashService $flashService
22
     * @param AssetManager $cacheManager
23
     */
24
    public function __construct(FlashService $flashService, AssetManager $assetManager)
25
    {
26
        parent::__construct($flashService);
27
28
        $this->assetManager = $assetManager;
29
    }
30
31
    /**
32
     * 404 page
33
     *
34
     * @param string $path
35
     *
36
     * @return Response The response
37
     */
38
    public function asset(string $path): Response
39
    {
40
        $content = $this->assetManager->renderRaw($path);
41
42
        if (null === $content) {
43
            return $this->create404();
44
        }
45
46
        $contentType = $this->getContentType($path);
47
48
        $response = new Response();
49
        $response->setContent($content);
50
51
        if ($contentType) {
52
            $response->getHeaders()->add('Content-Type', $contentType);
53
        }
54
55
        return $response;
56
    }
57
58
    /**
59
     * @param string $path
60
     *
61
     * @return string|null
62
     */
63
    protected function getContentType(string $path): ?string
64
    {
65
        $ext = substr($path, strrpos($path, '.'));
66
        switch ($ext) {
67
            case '.css':
68
                return 'text/css';
69
            case '.js':
70
                return 'text/css';
71
            case '.jpg':
72
            case '.jpeg':
73
                return 'image/jpeg';
74
            case '.png':
75
                return 'image/png';
76
            case '.gif':
77
                return 'image/gif';
78
            case '.svg':
79
                return 'image/svg+xml';
80
            case '.ico':
81
                return 'image/x-icon';
82
        }
83
84
        return null;
85
    }
86
87
    protected function create404(): Response
88
    {
89
        $this->view = $this->viewFactory->createView('contents/frontend/404');
90
91
        $response = $this->createResponse('404 Not Found');
92
        $response->setStatusCode(ResponseHeaders::HTTP_NOT_FOUND);
93
94
        return $response;
95
    }
96
}
97