1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Lepton\Core\Handler; |
4
|
|
|
use Lepton\Routing\Match\{Match404, MatchFile}; |
5
|
|
|
use Lepton\Http\Response\FileResponse; |
6
|
|
|
use Lepton\Core\Application; |
7
|
|
|
use Lepton\Http\Response\NotFoundResponse; |
8
|
|
|
|
9
|
|
|
class StaticHandler extends AbstractHandler |
10
|
|
|
{ |
11
|
|
|
public function resolveRequest() : MatchFile|Match404{ |
12
|
|
|
|
13
|
|
|
// Get the requested file path |
14
|
|
|
$url = $this->request->url; |
15
|
|
|
$url = preg_replace("/^".str_replace("/", "\/", Application::getAppConfig()->base_url)."\//", "", $url); |
16
|
|
|
|
17
|
|
|
|
18
|
|
|
$root = Application::$documentRoot; |
19
|
|
|
$root .= Application::getAppConfig()->base_url; |
20
|
|
|
$filePath = $root."/".Application::getAppConfig()->static_files_dir. "/". $url; |
21
|
|
|
|
22
|
|
|
// Check if the file exists |
23
|
|
|
if (file_exists($filePath)) { |
24
|
|
|
// Get the file extension |
25
|
|
|
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION); |
26
|
|
|
// Set content type based on the file extension |
27
|
|
|
switch ($fileExtension) { |
28
|
|
|
case 'png': |
29
|
|
|
$contentType = 'image/png'; |
30
|
|
|
break; |
31
|
|
|
case 'jpg': |
32
|
|
|
case 'jpeg': |
33
|
|
|
$contentType = 'image/jpeg'; |
34
|
|
|
break; |
35
|
|
|
case 'gif': |
36
|
|
|
$contentType = 'image/gif'; |
37
|
|
|
break; |
38
|
|
|
case 'css': |
39
|
|
|
$contentType = 'text/css'; |
40
|
|
|
break; |
41
|
|
|
case 'js': |
42
|
|
|
$contentType = 'text/javascript'; |
43
|
|
|
break; |
44
|
|
|
case 'pdf': |
45
|
|
|
$contentType = 'application/pdf'; |
46
|
|
|
break; |
47
|
|
|
default: |
48
|
|
|
$contentType = ''; |
49
|
|
|
break; |
50
|
|
|
} |
51
|
|
|
//die($contentType); |
52
|
|
|
return new MatchFile(filePath: $filePath, contentType: $contentType); |
53
|
|
|
} else { |
54
|
|
|
die($filePath); |
|
|
|
|
55
|
|
|
return new Match404(); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function handle($match): FileResponse|NotFoundResponse{ |
60
|
|
|
if($match instanceof Match404){ |
61
|
|
|
return new NotFoundResponse(); |
62
|
|
|
} |
63
|
|
|
return new FileResponse($match->filePath, $match->contentType); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.