Passed
Pull Request — master (#148)
by Sergei
14:04 queued 11:50
created

Serve   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 103
Duplicated Lines 0 %

Test Coverage

Coverage 95.56%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 13
eloc 51
c 3
b 0
f 0
dl 0
loc 103
ccs 43
cts 45
cp 0.9556
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isAddressTaken() 0 11 2
A configure() 0 9 1
B execute() 0 61 10
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\Input\InputArgument;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Input\InputOption;
11
use Symfony\Component\Console\Output\OutputInterface;
12
use Symfony\Component\Console\Style\SymfonyStyle;
13
use Yiisoft\Yii\Console\ExitCode;
14
15
use function explode;
16
use function fclose;
17
use function file_exists;
18
use function fsockopen;
19
use function getcwd;
20
use function is_dir;
21
use function passthru;
22
use function strpos;
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 44
    public function configure(): void
38
    {
39
        $this
40 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.')
41 44
            ->addArgument('address', InputArgument::OPTIONAL, 'Host to serve at', 'localhost')
42 44
            ->addOption('port', 'p', InputOption::VALUE_OPTIONAL, 'Port to serve at', self::DEFAULT_PORT)
43 44
            ->addOption('docroot', 't', InputOption::VALUE_OPTIONAL, 'Document root to serve from', self::DEFAULT_DOCROOT)
44 44
            ->addOption('router', 'r', InputOption::VALUE_OPTIONAL, 'Path to router script', self::DEFAULT_ROUTER)
45 44
            ->addOption('env', 'e', InputOption::VALUE_OPTIONAL, 'It is only used for testing.');
46
    }
47
48 5
    protected function execute(InputInterface $input, OutputInterface $output): int
49
    {
50 5
        $io = new SymfonyStyle($input, $output);
51
52
        /** @var string $address */
53 5
        $address = $input->getArgument('address');
54
55
        /** @var string $router */
56 5
        $router = $input->getOption('router');
57
58
        /** @var string $port */
59 5
        $port = $input->getOption('port');
60
61
        /** @var string $docroot */
62 5
        $docroot = $input->getOption('docroot');
63
64 5
        if ($router === self::DEFAULT_ROUTER && !file_exists(self::DEFAULT_ROUTER)) {
65 3
            $io->warning('Default router "' . self::DEFAULT_ROUTER . '" does not exist. Serving without router. URLs with dots may fail.');
66 3
            $router = null;
67
        }
68
69
        /** @var string $env */
70 5
        $env = $input->getOption('env');
71
72 5
        $documentRoot = getcwd() . '/' . $docroot; // TODO: can we do it better?
73
74 5
        if (strpos($address, ':') === false) {
75 4
            $address .= ':' . $port;
76
        }
77
78 5
        if (!is_dir($documentRoot)) {
79 1
            $io->error("Document root \"$documentRoot\" does not exist.");
80 1
            return self::EXIT_CODE_NO_DOCUMENT_ROOT;
81
        }
82
83 4
        if ($this->isAddressTaken($address)) {
84 1
            $io->error("http://$address is taken by another process.");
85 1
            return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
86
        }
87
88 3
        if ($router !== null && !file_exists($router)) {
89 1
            $io->error("Routing file \"$router\" does not exist.");
90 1
            return self::EXIT_CODE_NO_ROUTING_FILE;
91
        }
92
93 2
        $output->writeLn("Server started on <href=http://$address/>http://$address/</>");
94 2
        $output->writeLn("Document root is \"$documentRoot\"");
95
96 2
        if ($router) {
97 1
            $output->writeLn("Routing file is \"$router\"");
98
        }
99
100 2
        $output->writeLn('Quit the server with CTRL-C or COMMAND-C.');
101
102 2
        if ($env === 'test') {
103 2
            return ExitCode::OK;
104
        }
105
106
        passthru('"' . PHP_BINARY . '"' . " -S $address -t \"$documentRoot\" $router");
107
108
        return ExitCode::OK;
109
    }
110
111
    /**
112
     * @param string $address The server address.
113
     *
114
     * @return bool If address is already in use.
115
     */
116 4
    private function isAddressTaken(string $address): bool
117
    {
118 4
        [$hostname, $port] = explode(':', $address);
119 4
        $fp = @fsockopen($hostname, (int)$port, $errno, $errstr, 3);
120
121 4
        if ($fp === false) {
122 3
            return false;
123
        }
124
125 1
        fclose($fp);
126 1
        return true;
127
    }
128
}
129