Passed
Pull Request — master (#149)
by Rustam
02:16
created

Serve::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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\Aliases\Aliases;
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
final class Serve extends Command
26
{
27
    public const EXIT_CODE_NO_DOCUMENT_ROOT = 2;
28
    public const EXIT_CODE_NO_ROUTING_FILE = 3;
29
    public const EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS = 5;
30
31
    private const DEFAULT_PORT = '8080';
32
    private const DEFAULT_DOCROOT = 'public';
33
    private const DEFAULT_ROUTER = 'public/index.php';
34
35
    protected static $defaultName = 'serve';
36
    protected static $defaultDescription = 'Runs PHP built-in web server';
37
38 44
    public function __construct(private Aliases $aliases)
39
    {
40 44
        parent::__construct();
41
    }
42
43 44
    public function configure(): void
44
    {
45
        $this
46 44
            ->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.')
47 44
            ->addArgument('address', InputArgument::OPTIONAL, 'Host to serve at', '127.0.0.1')
48 44
            ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, 'Port to serve at', self::DEFAULT_PORT)
49 44
            ->addOption('docroot', 't', InputOption::VALUE_OPTIONAL, 'Document root to serve from', self::DEFAULT_DOCROOT)
50 44
            ->addOption('router', 'r', InputOption::VALUE_OPTIONAL, 'Path to router script', self::DEFAULT_ROUTER)
51 44
            ->addOption('env', 'e', InputOption::VALUE_OPTIONAL, 'It is only used for testing.');
52
    }
53
54
    public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
55
    {
56
        if ($input->mustSuggestArgumentValuesFor('address')) {
57
            $suggestions->suggestValues(['localhost', '127.0.0.1', '0.0.0.0']);
58
            return;
59
        }
60
61
        $suggestions->suggestOptions($this->getDefinition()->getOptions());
62
    }
63
64 5
    protected function execute(InputInterface $input, OutputInterface $output): int
65
    {
66 5
        $io = new SymfonyStyle($input, $output);
67
68
        /** @var string $address */
69 5
        $address = $input->getArgument('address');
70
71
        /** @var string $router */
72 5
        $router = $input->getOption('router');
73
74
        /** @var string $port */
75 5
        $port = $input->getOption('port');
76
77
        /** @var string $docroot */
78 5
        $docroot = $input->getOption('docroot');
79
80 5
        if ($router === self::DEFAULT_ROUTER && !file_exists(self::DEFAULT_ROUTER)) {
81 3
            $io->warning('Default router "' . self::DEFAULT_ROUTER . '" does not exist. Serving without router. URLs with dots may fail.');
82 3
            $router = null;
83
        }
84
85
        /** @var string $env */
86 5
        $env = $input->getOption('env');
87
88 5
        $documentRoot = $this->aliases->get('@root/' . $docroot);
89
90 5
        if (!str_contains($address, ':')) {
91 4
            $address .= ':' . $port;
92
        }
93
94 5
        if (!is_dir($documentRoot)) {
95 1
            $io->error("Document root \"$documentRoot\" does not exist.");
96 1
            return self::EXIT_CODE_NO_DOCUMENT_ROOT;
97
        }
98
99 4
        if ($this->isAddressTaken($address)) {
100 1
            $io->error("http://$address is taken by another process.");
101 1
            return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
102
        }
103
104 3
        if ($router !== null && !file_exists($router)) {
105 1
            $io->error("Routing file \"$router\" does not exist.");
106 1
            return self::EXIT_CODE_NO_ROUTING_FILE;
107
        }
108
109 2
        $output->writeLn("Server started on <href=http://$address/>http://$address/</>");
110 2
        $output->writeLn("Document root is \"$documentRoot\"");
111
112 2
        if ($router) {
113 1
            $output->writeLn("Routing file is \"$router\"");
114
        }
115
116 2
        $output->writeLn('Quit the server with CTRL-C or COMMAND-C.');
117
118 2
        if ($env === 'test') {
119 2
            return ExitCode::OK;
120
        }
121
122
        passthru('"' . PHP_BINARY . '"' . " -S $address -t $documentRoot $router");
123
124
        return ExitCode::OK;
125
    }
126
127
    /**
128
     * @param string $address The server address.
129
     *
130
     * @return bool If address is already in use.
131
     */
132 4
    private function isAddressTaken(string $address): bool
133
    {
134 4
        [$hostname, $port] = explode(':', $address);
135 4
        $fp = @fsockopen($hostname, (int)$port, $errno, $errstr, 3);
136
137 4
        if ($fp === false) {
138 3
            return false;
139
        }
140
141 1
        fclose($fp);
142 1
        return true;
143
    }
144
}
145