Passed
Pull Request — master (#158)
by Alexander
02:25
created

Serve::execute()   B

Complexity

Conditions 10
Paths 28

Size

Total Lines 61
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 10.0268

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 30
c 3
b 0
f 0
dl 0
loc 61
ccs 29
cts 31
cp 0.9355
rs 7.6666
cc 10
nc 28
nop 2
crap 10.0268

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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