Passed
Pull Request — master (#164)
by
unknown
22:59 queued 10:27
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\Command\Command;
8
use Symfony\Component\Console\Completion\CompletionInput;
9
use Symfony\Component\Console\Completion\CompletionSuggestions;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Style\SymfonyStyle;
15
use Yiisoft\Yii\Console\ExitCode;
16
17
use function explode;
18
use function fclose;
19
use function file_exists;
20
use function fsockopen;
21
use function is_dir;
22
use function passthru;
23
24
final class Serve extends Command
25
{
26
    public const EXIT_CODE_NO_DOCUMENT_ROOT = 2;
27
    public const EXIT_CODE_NO_ROUTING_FILE = 3;
28
    public const EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS = 5;
29
30
    private string $defaultAddress;
31
    private string $defaultPort;
32
    private string $defaultDocroot;
33
    private string $defaultRouter;
34
    private int $defaultWorkers;
35
36
    protected static $defaultName = 'serve';
37
    protected static $defaultDescription = 'Runs PHP built-in web server';
38
39
    /**
40
     * @param string|null $appRootPath
41
     * @param array|null $options
42
     * @psalm-param array{
43
     *     address?:non-empty-string,
44
     *     port?:non-empty-string,
45
     *     docroot?:string,
46
     *     router?:string
47
     * } $options
48
     */
49 46
    public function __construct(private ?string $appRootPath = null, ?array $options = [])
50
    {
51 46
        $this->defaultAddress = $options['address'] ?? '127.0.0.1';
52 46
        $this->defaultPort = $options['port'] ?? '8080';
53 46
        $this->defaultDocroot = $options['docroot'] ?? 'public';
54 46
        $this->defaultRouter = $options['router'] ?? 'public/index.php';
55 46
        $this->defaultWorkers = (int) ($options['workers'] ?? 2);
56
57 46
        parent::__construct();
58
    }
59
60 46
    public function configure(): void
61
    {
62
        $this
63 46
            ->setHelp('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.')
64 46
            ->addArgument('address', InputArgument::OPTIONAL, 'Host to serve at', $this->defaultAddress)
65 46
            ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, 'Port to serve at', $this->defaultPort)
66 46
            ->addOption('docroot', 't', InputOption::VALUE_OPTIONAL, 'Document root to serve from', $this->defaultDocroot)
67 46
            ->addOption('router', 'r', InputOption::VALUE_OPTIONAL, 'Path to router script', $this->defaultRouter)
68 46
            ->addOption('workers', 'w', InputOption::VALUE_OPTIONAL, 'Workers number the server will start with', $this->defaultWorkers)
69 46
            ->addOption('env', 'e', InputOption::VALUE_OPTIONAL, 'It is only used for testing.');
70
    }
71
72 1
    public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
73
    {
74 1
        if ($input->mustSuggestArgumentValuesFor('address')) {
75 1
            $suggestions->suggestValues(['localhost', '127.0.0.1', '0.0.0.0']);
76 1
            return;
77
        }
78
    }
79
80 6
    protected function execute(InputInterface $input, OutputInterface $output): int
81
    {
82 6
        $io = new SymfonyStyle($input, $output);
83
84
        /** @var string $address */
85 6
        $address = $input->getArgument('address');
86
87
        /** @var string $router */
88 6
        $router = $input->getOption('router');
89 6
        $workers = (int) $input->getOption('workers');
90
91
        /** @var string $port */
92 6
        $port = $input->getOption('port');
93
94
        /** @var string $docroot */
95 6
        $docroot = $input->getOption('docroot');
96
97 6
        if ($router === $this->defaultRouter && !file_exists($this->defaultRouter)) {
98 4
            $io->warning('Default router "' . $this->defaultRouter . '" does not exist. Serving without router. URLs with dots may fail.');
99 4
            $router = null;
100
        }
101
102
        /** @var string $env */
103 6
        $env = $input->getOption('env');
104
105 6
        $documentRoot = $this->getRootPath() . DIRECTORY_SEPARATOR . $docroot;
106
107 6
        if (!str_contains($address, ':')) {
108 5
            $address .= ':' . $port;
109
        }
110
111 6
        if (!is_dir($documentRoot)) {
112 1
            $io->error("Document root \"$documentRoot\" does not exist.");
113 1
            return self::EXIT_CODE_NO_DOCUMENT_ROOT;
114
        }
115
116 5
        if ($this->isAddressTaken($address)) {
117 1
            $io->error("http://$address is taken by another process.");
118 1
            return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
119
        }
120
121 4
        if ($router !== null && !file_exists($router)) {
122 1
            $io->error("Routing file \"$router\" does not exist.");
123 1
            return self::EXIT_CODE_NO_ROUTING_FILE;
124
        }
125
126 3
        $output->writeLn("Server started on <href=http://$address/>http://$address/</>");
127 3
        $output->writeLn("Document root is \"$documentRoot\"");
128
129 3
        if ($router) {
130 1
            $output->writeLn("Routing file is \"$router\"");
131
        }
132
133 3
        $output->writeLn('Quit the server with CTRL-C or COMMAND-C.');
134
135 3
        if ($env === 'test') {
136 3
            return ExitCode::OK;
137
        }
138
139
        passthru('PHP_CLI_SERVER_WORKERS=' . $workers . ' "' . PHP_BINARY . '"' . " -S $address -t \"$documentRoot\" $router");
140
141
        return ExitCode::OK;
142
    }
143
144
    /**
145
     * @param string $address The server address.
146
     *
147
     * @return bool If address is already in use.
148
     */
149 5
    private function isAddressTaken(string $address): bool
150
    {
151 5
        [$hostname, $port] = explode(':', $address);
152 5
        $fp = @fsockopen($hostname, (int)$port, $errno, $errstr, 3);
153
154 5
        if ($fp === false) {
155 4
            return false;
156
        }
157
158 1
        fclose($fp);
159 1
        return true;
160
    }
161
162 6
    private function getRootPath(): string
163
    {
164 6
        if ($this->appRootPath !== null) {
165
            return rtrim($this->appRootPath, DIRECTORY_SEPARATOR);
166
        }
167
168 6
        return getcwd();
169
    }
170
}
171