Passed
Push — master ( 9ecf35...f44701 )
by Rustam
21:24 queued 18:18
created

Serve::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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