BuiltinServer::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 1
nop 4
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace mpyw\HyperBuiltinServer\Internal;
4
use React\ChildProcess\Process;
5
6
class BuiltinServer extends Process
7
{
8
    protected $host;
9
    protected $port;
10
11
    public function __construct($host = '127.0.0.1', $docroot = null, $router = null, $php = PHP_BINARY)
12
    {
13
        $port = mt_rand(49152, 65535);
14
        $command = implode(' ', array_filter([
15
            escapeshellarg($php),
16
            '-S',
17
            escapeshellarg("$host:$port"),
18
            $docroot !== null ? ('-t ' . escapeshellarg($docroot)) : null,
19
            $router !== null ? escapeshellarg($router) : null,
20
        ], 'is_string'));
21
        parent::__construct($command, null, null, ['bypass_shell' => true]);
22
        $this->host = $host;
23
        $this->port = $port;
24
    }
25
26
    public function getSocketClient()
27
    {
28
        $socket = @stream_socket_client("tcp://{$this->host}:{$this->port}");
29
        if ($socket === false) {
30
            throw new \RuntimeException(error_get_last()['message']);
31
        }
32
        return $socket;
33
    }
34
}
35