Passed
Push — master ( fb47d8...1d2cc1 )
by Alexander
02:25
created

Serve::isAddressTaken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 10
cc 2
nc 2
nop 1
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\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
    protected static $defaultDescription = 'Runs PHP built-in web server';
27
28 5
    public function configure(): void
29
    {
30
        $this
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
        /** @var string $env */
61 5
        $env = $input->getOption('env');
62
63 5
        $documentRoot = getcwd() . '/' . $docroot; // TODO: can we do it better?
64
65 5
        if (strpos($address, ':') === false) {
66 4
            $address .= ':' . $port;
67
        }
68
69 5
        if (!is_dir($documentRoot)) {
70 1
            $io->error("Document root \"$documentRoot\" does not exist.");
71 1
            return self::EXIT_CODE_NO_DOCUMENT_ROOT;
72
        }
73
74 4
        if ($this->isAddressTaken($address)) {
75 1
            $io->error("http://$address is taken by another process.");
76 1
            return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
77
        }
78
79 3
        if ($router !== null && !file_exists($router)) {
80 1
            $io->error("Routing file \"$router\" does not exist.");
81 1
            return self::EXIT_CODE_NO_ROUTING_FILE;
82
        }
83
84 2
        $output->writeLn("Server started on <href=http://{$address}/>http://{$address}/</>");
85 2
        $output->writeLn("Document root is \"{$documentRoot}\"");
86
87 2
        if ($router) {
88 1
            $output->writeLn("Routing file is \"$router\"");
89
        }
90
91 2
        $output->writeLn('Quit the server with CTRL-C or COMMAND-C.');
92
93 2
        if ($env === 'test') {
94 2
            return ExitCode::OK;
95
        }
96
97
        passthru('"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $router");
98
99
        return ExitCode::OK;
100
    }
101
102
    /**
103
     * @param string $address server address
104
     *
105
     * @return bool if address is already in use
106
     */
107 4
    private function isAddressTaken(string $address): bool
108
    {
109 4
        [$hostname, $port] = explode(':', $address);
110 4
        $fp = @fsockopen($hostname, (int)$port, $errno, $errstr, 3);
111 4
        if ($fp === false) {
112 3
            return false;
113
        }
114 1
        fclose($fp);
115 1
        return true;
116
    }
117
}
118