CanPretendToBeAFile   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 34
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A httpDate() 0 3 2
A pretendResponseIsFile() 0 20 2
A matchesCache() 0 5 2
1
<?php
2
3
namespace Usernotnull\Toast\Controllers;
4
5
use Illuminate\Http\Response;
6
use Illuminate\Support\Facades\File;
7
use Illuminate\Support\Facades\Request;
8
use Symfony\Component\HttpFoundation\BinaryFileResponse;
9
10
use function is_string;
11
12
trait CanPretendToBeAFile
13
{
14
    protected function httpDate(int|false $timestamp): string
15
    {
16
        return sprintf('%s GMT', gmdate('D, d M Y H:i:s', $timestamp ?: null));
17
    }
18
19
    protected function matchesCache(int|false $lastModified): bool
20
    {
21
        $modifiedSince = Request::server('HTTP_IF_MODIFIED_SINCE', '');
22
23
        return is_string($modifiedSince) && strtotime($modifiedSince) === $lastModified;
24
    }
25
26
    public function pretendResponseIsFile(
27
        string $file,
28
        string $mimeType = 'application/javascript'
29
    ): Response|BinaryFileResponse {
30
        $expires = strtotime('+1 year');
31
        $lastModified = File::lastModified($file);
32
        $cacheControl = 'public, max-age=31536000';
33
34
        if ($this->matchesCache($lastModified)) {
35
            return response()->make('', 304, [
36
                'Expires' => $this->httpDate($expires),
37
                'Cache-Control' => $cacheControl,
38
            ]);
39
        }
40
41
        return response()->file($file, [
42
            'Content-Type' => "$mimeType; charset=utf-8",
43
            'Expires' => $this->httpDate($expires),
44
            'Cache-Control' => $cacheControl,
45
            'Last-Modified' => $this->httpDate($lastModified),
46
        ]);
47
    }
48
}
49