|
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
|
|
|
|