Passed
Push — master ( b828ba...0fd940 )
by Alexander
02:07
created

Serve   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Test Coverage

Coverage 95.74%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 13
eloc 52
c 3
b 0
f 0
dl 0
loc 100
ccs 45
cts 47
cp 0.9574
rs 10

3 Methods

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