-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathRouter.php
110 lines (90 loc) · 2.93 KB
/
Router.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
namespace Hyde\RealtimeCompiler\Routing;
use Desilva\Microserve\JsonResponse;
use Desilva\Microserve\Request;
use Desilva\Microserve\Response;
use Hyde\RealtimeCompiler\Actions\AssetFileLocator;
use Hyde\RealtimeCompiler\Actions\RendersSearchPage;
use Hyde\RealtimeCompiler\Concerns\SendsErrorResponses;
use Hyde\RealtimeCompiler\Http\HtmlResponse;
use Hyde\RealtimeCompiler\Models\FileObject;
class Router
{
use SendsErrorResponses;
protected Request $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function handle(): Response
{
if ($this->shouldProxy($this->request)) {
return $this->proxyStatic();
}
if ($this->shouldRenderSpecial($this->request)) {
if ($this->request->path === '/docs') {
$this->request->path = '/docs/index';
}
if ($this->request->path === '/docs/search') {
return new HtmlResponse(200, 'OK', [
'body' => (new RendersSearchPage())->__invoke(),
]);
}
if ($this->request->path === '/ping') {
return new JsonResponse(200, 'OK', [
'server' => 'Hyde/RealtimeCompiler',
]);
}
}
return PageRouter::handle($this->request);
}
/**
* If the request is not for a web page, we assume it's
* a static asset, which we instead want to proxy.
*/
protected function shouldProxy(Request $request): bool
{
// Always proxy media files
if (str_starts_with($request->path, '/media/')) {
return true;
}
// Get the requested file extension
$extension = pathinfo($request->path)['extension'] ?? null;
// If the extension is not set (pretty url), or is .html,
//we assume it's a web page which we need to compile.
if ($extension === null || $extension === 'html') {
return false;
}
// The page is not a web page, so we assume it should be proxied.
return true;
}
/**
* Proxy a static file or return a 404.
*/
protected function proxyStatic(): Response
{
$path = AssetFileLocator::find($this->request->path);
if ($path === null) {
return $this->notFound();
}
$file = new FileObject($path);
return (new Response(200, 'OK', [
'body' => $file->getStream(),
]))->withHeaders([
'Content-Type' => $file->getMimeType(),
'Content-Length' => $file->getContentLength(),
]);
}
/**
* If the request is for a special page, we handle it here.
*/
protected function shouldRenderSpecial(Request $request): bool
{
$routes = [
'/ping',
'/docs',
'/docs/search',
];
return in_array($request->path, $routes);
}
}