Passed
Pull Request — master (#211)
by Dmitriy
02:34
created

Serve::complete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Console\Command;
6
7
use Symfony\Component\Console\Attribute\AsCommand;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Completion\CompletionInput;
10
use Symfony\Component\Console\Completion\CompletionSuggestions;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
use Symfony\Component\Console\Style\SymfonyStyle;
16
use Yiisoft\Yii\Console\ExitCode;
17
18
use function explode;
19
use function fclose;
20
use function file_exists;
21
use function fsockopen;
22
use function is_dir;
23
use function passthru;
24
25
#[AsCommand('serve', 'Runs PHP built-in web server')]
26
final class Serve extends Command
27
{
28
    public const EXIT_CODE_NO_DOCUMENT_ROOT = 2;
29
    public const EXIT_CODE_NO_ROUTING_FILE = 3;
30
    public const EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS = 5;
31
32
    private string $defaultAddress;
33
    private string $defaultPort;
34
    private string $defaultDocroot;
35
    private string $defaultRouter;
36
    private int $defaultWorkers;
37
38
    /**
39
     * @psalm-param array{
40
     *     address?:non-empty-string,
41
     *     port?:non-empty-string,
42
     *     docroot?:string,
43
     *     router?:string,
44
     *     workers?:int|string
45
     * } $options
46
     */
47 49
    public function __construct(private ?string $appRootPath = null, ?array $options = [])
48
    {
49 49
        $this->defaultAddress = $options['address'] ?? '127.0.0.1';
50 49
        $this->defaultPort = $options['port'] ?? '8080';
51 49
        $this->defaultDocroot = $options['docroot'] ?? 'public';
52 49
        $this->defaultRouter = $options['router'] ?? 'public/index.php';
53 49
        $this->defaultWorkers = (int) ($options['workers'] ?? 2);
54
55 49
        parent::__construct();
56
    }
57
58 49
    public function configure(): void
59
    {
60 49
        $this
61 49
            ->setHelp(
62 49
                'In order to access server from remote machines use 0.0.0.0:8000. That is especially useful when running server in a virtual machine.'
63 49
            )
64 49
            ->addArgument('address', InputArgument::OPTIONAL, 'Host to serve at', $this->defaultAddress)
65 49
            ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, 'Port to serve at', $this->defaultPort)
66 49
            ->addOption(
67 49
                'docroot',
68 49
                't',
69 49
                InputOption::VALUE_OPTIONAL,
70 49
                'Document root to serve from',
71 49
                $this->defaultDocroot
72 49
            )
73 49
            ->addOption('router', 'r', InputOption::VALUE_OPTIONAL, 'Path to router script', $this->defaultRouter)
74 49
            ->addOption(
75 49
                'workers',
76 49
                'w',
77 49
                InputOption::VALUE_OPTIONAL,
78 49
                'Workers number the server will start with',
79 49
                $this->defaultWorkers
80 49
            )
81 49
            ->addOption('env', 'e', InputOption::VALUE_OPTIONAL, 'It is only used for testing.')
82 49
            ->addOption('open', 'o', InputOption::VALUE_OPTIONAL, 'Opens the serving server in the default browser.', false)
83 49
            ->addOption('xdebug', 'x', InputOption::VALUE_OPTIONAL, 'Enables XDEBUG session.', false);
84
    }
85
86 1
    public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
87
    {
88 1
        if ($input->mustSuggestArgumentValuesFor('address')) {
89 1
            $suggestions->suggestValues(['localhost', '127.0.0.1', '0.0.0.0']);
90 1
            return;
91
        }
92
    }
93
94 6
    protected function execute(InputInterface $input, OutputInterface $output): int
95
    {
96 6
        $io = new SymfonyStyle($input, $output);
97 6
        $io->title('Yii3 Development Server');
98 6
        $io->writeln('https://yiiframework.com' . "\n");
99
100
        /** @var string $address */
101 6
        $address = $input->getArgument('address');
102
103
        /** @var string $router */
104 6
        $router = $input->getOption('router');
105 6
        $workers = (int) $input->getOption('workers');
106
107
        /** @var string $port */
108 6
        $port = $input->getOption('port');
109
110
        /** @var string $docroot */
111 6
        $docroot = $input->getOption('docroot');
112
113 6
        if ($router === $this->defaultRouter && !file_exists($this->defaultRouter)) {
114 4
            $io->warning(
115 4
                'Default router "' . $this->defaultRouter . '" does not exist. Serving without router. URLs with dots may fail.'
116 4
            );
117 4
            $router = null;
118
        }
119
120
        /** @var string $env */
121 6
        $env = $input->getOption('env');
122
123 6
        $documentRoot = $this->getRootPath() . DIRECTORY_SEPARATOR . $docroot;
124
125 6
        if (!str_contains($address, ':')) {
126 6
            $address .= ':' . $port;
127
        } else {
128
            $port = explode(':', $address)[1];
129
        }
130
131 6
        if (!is_dir($documentRoot)) {
132 1
            $io->error("Document root \"$documentRoot\" does not exist.");
133 1
            return self::EXIT_CODE_NO_DOCUMENT_ROOT;
134
        }
135
136 5
        if ($this->isAddressTaken($address)) {
137 1
            if ($this->isWindows()) {
138
                $io->error("Port {$port} is taken by another process.");
139
                return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
140
            }
141
142
            /** @psalm-suppress ForbiddenCode */
143 1
            $runningCommandPIDs = trim((string) shell_exec('lsof -ti :8080 -s TCP:LISTEN'));
144 1
            if (empty($runningCommandPIDs)) {
145 1
                $io->error("Port {$port} is taken by another process.");
146 1
                return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
147
            }
148
149
            $runningCommandPIDs = array_filter(explode("\n", $runningCommandPIDs));
150
            sort($runningCommandPIDs);
151
152
            $io->block(
153
                [
154
                    "Port {$port} is taken by the processes:",
155
                    ...array_map(
156
                        fn ($pid) => sprintf(
157
                            '#%s: %s',
158
                            $pid,
159
                            /** @psalm-suppress ForbiddenCode */
160
                            shell_exec("ps -o command= -p {$pid}"),
161
                        ),
162
                        $runningCommandPIDs,
163
                    ),
164
                ],
165
                'ERROR',
166
                'error',
167
            );
168
            if (!$io->confirm('Kill the process', true)) {
169
                return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
170
            }
171
            $io->info([
172
                'Stopping the processes...',
173
            ]);
174
            $out = array_filter(
175
                array_map(
176
                    /** @psalm-suppress ForbiddenCode */
177
                    fn ($pid) => shell_exec("kill -9 {$pid}"),
178
                    $runningCommandPIDs,
179
                )
180
            );
181
            if (!empty($out)) {
182
                $io->error($out);
183
                return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
184
            }
185
        }
186
187 4
        if ($router !== null && !file_exists($router)) {
188 1
            $io->error("Routing file \"$router\" does not exist.");
189 1
            return self::EXIT_CODE_NO_ROUTING_FILE;
190
        }
191
192 3
        $command = [];
193
194 3
        $isLinux = DIRECTORY_SEPARATOR !== '\\';
195
196 3
        if ($isLinux) {
197 3
            $command[] = 'PHP_CLI_SERVER_WORKERS=' . $workers;
198
        }
199
200 3
        $xDebugInstalled = extension_loaded('xdebug');
201 3
        $xDebugEnabled = $isLinux && $xDebugInstalled && $input->hasOption('xdebug') && $input->getOption(
202 3
            'xdebug'
203 3
        ) === null;
204
205 3
        if ($xDebugEnabled) {
206
            $command[] = 'XDEBUG_MODE=debug XDEBUG_TRIGGER=yes';
207
        }
208 3
        $outputTable = [];
209 3
        $outputTable[] = ['PHP', PHP_VERSION];
210 3
        $outputTable[] = [
211 3
            'xDebug',
212 3
            $xDebugInstalled ? sprintf(
213 3
                '%s, %s',
214 3
                phpversion('xdebug'),
215 3
                $xDebugEnabled ? '<info> Enabled </>' : '<error> Disabled </>',
216 3
            ) : '<error>Not installed</>',
217 3
            '--xdebug',
218 3
        ];
219 3
        $outputTable[] = ['Workers', $isLinux ? $workers : 'Not supported', '--workers, -w'];
220 3
        $outputTable[] = ['Address', $address];
221 3
        $outputTable[] = ['Document root', $documentRoot, '--docroot, -t'];
222 3
        $outputTable[] = ($router ? ['Routing file', $router, '--router, -r'] : []);
223
224 3
        $io->table(['Configuration', null, 'Options'], $outputTable);
225
226 3
        $command[] = '"' . PHP_BINARY . '"' . " -S $address -t \"$documentRoot\" $router";
227 3
        $command = implode(' ', $command);
228
229 3
        $output->writeln([
230 3
            'Executing: ',
231 3
            sprintf('<info>%s</>', $command),
232 3
        ], OutputInterface::VERBOSITY_VERBOSE);
233
234 3
        $io->success('Quit the server with CTRL-C or COMMAND-C.');
235
236 3
        if ($env === 'test') {
237 3
            return ExitCode::OK;
238
        }
239
240
        $openInBrowser = $input->hasOption('open') && $input->getOption('open') === null;
241
242
        if ($openInBrowser) {
243
            passthru('open http://' . $address);
244
        }
245
        passthru($command, $result);
246
247
        return $result;
248
    }
249
250
    /**
251
     * @param string $address The server address.
252
     *
253
     * @return bool If address is already in use.
254
     */
255 5
    private function isAddressTaken(string $address): bool
256
    {
257 5
        [$hostname, $port] = explode(':', $address);
258 5
        $fp = @fsockopen($hostname, (int) $port, $errno, $errstr, 3);
259
260 5
        if ($fp === false) {
261 4
            return false;
262
        }
263
264 1
        fclose($fp);
265 1
        return true;
266
    }
267
268 6
    private function getRootPath(): string
269
    {
270 6
        if ($this->appRootPath !== null) {
271
            return rtrim($this->appRootPath, DIRECTORY_SEPARATOR);
272
        }
273
274 6
        return getcwd();
275
    }
276
277 1
    private function isWindows(): bool
278
    {
279 1
        return stripos(PHP_OS, 'Win') === 0;
280
    }
281
}
282