-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServeCommand.php
More file actions
223 lines (179 loc) · 7.02 KB
/
Copy pathServeCommand.php
File metadata and controls
223 lines (179 loc) · 7.02 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
declare(strict_types=1);
namespace Zero\Lib\Console\Commands;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Zero\Lib\Console\Application;
use Zero\Lib\Console\Command\CommandInterface;
final class ServeCommand implements CommandInterface
{
public function getName(): string
{
return 'serve';
}
public function getDescription(): string
{
return 'Start the development server';
}
public function getUsage(): string
{
return 'php zero serve [--host=127.0.0.1] [--port=8000] [--root=public] [--watch] [--franken] [--swolee]';
}
public function execute(array $argv): int
{
// Parse "--key=value" options and "--flag" switches directly from argv.
// (getopt() can't be used here: it stops at the first non-option operand,
// i.e. the "serve" sub-command, so any --host/--port after it are ignored.)
$options = [];
foreach ($argv as $arg) {
if (! is_string($arg) || ! str_starts_with($arg, '--')) {
continue;
}
$body = substr($arg, 2);
if ($body === '') {
continue;
}
if (str_contains($body, '=')) {
[$key, $value] = explode('=', $body, 2);
$options[$key] = $value;
} else {
$options[$body] = true;
}
}
$host = $options['host'] ?? env('HOST', Application::DEFAULT_HOST);
$port = $options['port'] ?? env('PORT', Application::DEFAULT_PORT);
$root = $options['root'] ?? env('DOCROOT', Application::DEFAULT_DOCROOT);
$watch = array_key_exists('watch', $options ?? []);
if (! is_dir($root)) {
\Zero\Lib\Log::channel('internal')->error("Error: The specified document root \"{$root}\" does not exist.");
return 1;
}
if (array_key_exists('franken', $options ?? [])) {
$this->startFrankenServer($host, $port, $root, $watch);
return 0;
}
if (array_key_exists('swolee', $options ?? [])) {
if (! extension_loaded('swoole')) {
\Zero\Lib\Log::channel('internal')->error('Error: The Swoole extension is not installed.');
return 1;
}
$this->startSwooleServer($host, $port, $root, $watch);
return 0;
}
\Zero\Lib\Log::channel('internal')->info('Starting PHP server in default mode...');
$this->startPhpServer($host, $port, $root, $watch);
return 0;
}
private function startPhpServer(string $host, string $port, string $root, bool $watch): void
{
if ($watch) {
$this->startWatch($root, $host, $port);
}
$address = escapeshellarg($host . ':' . $port);
$command = sprintf('php -S %s -t %s', $address, escapeshellarg($root));
if (! $this->runCommand($command)) {
\Zero\Lib\Log::channel('internal')->error(
'Error: Unable to execute the PHP built-in server. Ensure passthru, system, exec, or shell_exec is enabled.'
);
}
}
private function startFrankenServer(string $host, string $port, string $root, bool $watch): void
{
if ($watch) {
$this->startWatch($root, $host, $port);
}
\Zero\Lib\Log::channel('internal')->info('Running Franken server...');
\Zero\Lib\Log::channel('internal')->info("Host: {$host}, Port: {$port}, Document Root: {$root}");
\Zero\Lib\Log::channel('internal')->info('Franken mode started...');
}
private function startSwooleServer(string $host, string $port, string $root, bool $watch): void
{
if ($watch) {
$this->startWatch($root, $host, $port);
}
$server = new \Swoole\Http\Server($host, (int) $port);
$server->on('Request', function ($request, $response) use ($root) {
$file = $root . $request->server['request_uri'];
if (file_exists($file)) {
$response->header('Content-Type', mime_content_type($file) ?: 'text/plain');
$response->send(file_get_contents($file) ?: '');
} else {
$response->status(404);
$response->end('Not Found');
}
});
\Zero\Lib\Log::channel('internal')->info("Swoole server started at http://{$host}:{$port}...");
$server->start();
}
private function startWatch(string $directory, string $host, string $port): void
{
\Zero\Lib\Log::channel('internal')->info("Watching for file changes in {$directory}...");
$address = escapeshellarg($host . ':' . $port);
$command = sprintf('php -S %s -t %s', $address, escapeshellarg($directory));
if (function_exists('inotify_init')) {
$inotify = inotify_init();
stream_set_blocking($inotify, false);
inotify_add_watch($inotify, $directory, IN_MODIFY | IN_CREATE | IN_DELETE);
while (true) {
$events = inotify_read($inotify);
if (! empty($events)) {
\Zero\Lib\Log::channel('internal')->info('File change detected, restarting server...');
$this->runCommand($command);
}
usleep(500000);
}
}
$lastModified = $this->getLastModifiedTime($directory);
while (true) {
clearstatcache();
$current = $this->getLastModifiedTime($directory);
if ($current > $lastModified) {
$lastModified = $current;
\Zero\Lib\Log::channel('internal')->info('File change detected, restarting server...');
$this->runCommand($command);
}
usleep(500000);
}
}
private function getLastModifiedTime(string $directory): int
{
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS));
$lastModified = 0;
foreach ($iterator as $file) {
if ($file->isFile()) {
$lastModified = max($lastModified, $file->getMTime());
}
}
return $lastModified;
}
private function runCommand(string $command): bool
{
if (\function_exists('passthru')) {
$status = 0;
\passthru($command, $status);
return true;
}
if (\function_exists('system')) {
$status = 0;
\system($command, $status);
return true;
}
if (\function_exists('exec')) {
$output = [];
$status = 0;
\exec($command, $output, $status);
if ($output !== []) {
echo implode(PHP_EOL, $output) . PHP_EOL;
}
return true;
}
if (\function_exists('shell_exec')) {
$output = \shell_exec($command);
if ($output !== null) {
echo $output;
return true;
}
}
return false;
}
}