Passed
Push — master ( a7d8e3...a6d3c6 )
by Dmitriy
05:10 queued 04:35
created

Serve   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 200
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 109
c 5
b 0
f 0
dl 0
loc 200
ccs 105
cts 112
cp 0.9375
rs 10
wmc 28

6 Methods

Rating   Name   Duplication   Size   Complexity  
A complete() 0 5 2
A __construct() 0 9 1
A getRootPath() 0 7 2
A isAddressTaken() 0 11 2
A configure() 0 26 1
F execute() 0 104 20
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.')
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 5
            $address .= ':' . $port;
127
        }
128
129 6
        if (!is_dir($documentRoot)) {
130 1
            $io->error("Document root \"$documentRoot\" does not exist.");
131 1
            return self::EXIT_CODE_NO_DOCUMENT_ROOT;
132
        }
133
134 5
        if ($this->isAddressTaken($address)) {
135 1
            $io->error("http://$address is taken by another process.");
136 1
            return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
137
        }
138
139 4
        if ($router !== null && !file_exists($router)) {
140 1
            $io->error("Routing file \"$router\" does not exist.");
141 1
            return self::EXIT_CODE_NO_ROUTING_FILE;
142
        }
143
144 3
        $command = [];
145
146 3
        $isLinux = DIRECTORY_SEPARATOR !== '\\';
147
148 3
        if ($isLinux) {
149 3
            $command[] = 'PHP_CLI_SERVER_WORKERS=' . $workers;
150
        }
151
152 3
        $xDebugInstalled = extension_loaded('xdebug');
153 3
        $xDebugEnabled = $isLinux && $xDebugInstalled && $input->hasOption('xdebug') && $input->getOption('xdebug') === null;
154
155 3
        if ($xDebugEnabled) {
156
            $command[] = 'XDEBUG_MODE=debug XDEBUG_TRIGGER=yes';
157
        }
158 3
        $outputTable = [];
159 3
        $outputTable[] = ['PHP', PHP_VERSION];
160 3
        $outputTable[] = [
161 3
            'xDebug',
162 3
            $xDebugInstalled ? sprintf(
163 3
                '%s, %s',
164 3
                phpversion('xdebug'),
165 3
                $xDebugEnabled ? '<info> Enabled </>' : '<error> Disabled </>',
166 3
            ) : '<error>Not installed</>',
167 3
            '--xdebug',
168 3
        ];
169 3
        $outputTable[] = ['Workers', $isLinux ? $workers : 'Not supported', '--workers, -w'];
170 3
        $outputTable[] = ['Address', $address];
171 3
        $outputTable[] = ['Document root', $documentRoot, '--docroot, -t'];
172 3
        $outputTable[] = ($router ? ['Routing file', $router, '--router, -r'] : []);
173
174 3
        $io->table(['Configuration', null, 'Options'], $outputTable);
175
176 3
        $command[] = '"' . PHP_BINARY . '"' . " -S $address -t \"$documentRoot\" $router";
177 3
        $command = implode(' ', $command);
178
179 3
        $output->writeln([
180 3
            'Executing: ',
181 3
            sprintf('<info>%s</>', $command),
182 3
        ], OutputInterface::VERBOSITY_VERBOSE);
183
184 3
        $io->success('Quit the server with CTRL-C or COMMAND-C.');
185
186 3
        if ($env === 'test') {
187 3
            return ExitCode::OK;
188
        }
189
190
        $openInBrowser = $input->hasOption('open') && $input->getOption('open') === null;
191
192
        if ($openInBrowser) {
193
            passthru('open http://' . $address);
194
        }
195
        passthru($command, $result);
196
197
        return $result;
198
    }
199
200
    /**
201
     * @param string $address The server address.
202
     *
203
     * @return bool If address is already in use.
204
     */
205 5
    private function isAddressTaken(string $address): bool
206
    {
207 5
        [$hostname, $port] = explode(':', $address);
208 5
        $fp = @fsockopen($hostname, (int) $port, $errno, $errstr, 3);
209
210 5
        if ($fp === false) {
211 4
            return false;
212
        }
213
214 1
        fclose($fp);
215 1
        return true;
216
    }
217
218 6
    private function getRootPath(): string
219
    {
220 6
        if ($this->appRootPath !== null) {
221
            return rtrim($this->appRootPath, DIRECTORY_SEPARATOR);
222
        }
223
224 6
        return getcwd();
225
    }
226
}
227