Completed
Push — master ( 229ed6...97fb3b )
by Marcel
04:38
created

ConcurrentServer::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UMA\JsonRpc;
6
7
use UMA\JsonRpc\Internal\Input;
8
9
/**
10
 * Experimental concurrent Server. Needs the pcntl extension,
11
 * therefore it can only work in the CLI SAPI.
12
 *
13
 * /!\ Probably NOT fit for production usage.
14
 */
15
class ConcurrentServer extends Server
16
{
17
    protected function batch(Input $input): ?string
18 16
    {
19
        \assert($input->isArray());
20 16
21
        $children = [];
22
        $responses = [];
23
        foreach ($input->data() as $request) {
24 16
            $pair = \stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
25
26 16
            $pid = \pcntl_fork();
27 16
28
            if (0 === $pid) {
29 6
                \fclose($pair[0]);
30
31 6
                \fwrite($pair[1], $this->single(Input::fromSafeData($request)) . "\n");
32
33 6
                \fclose($pair[1]);
34 1
35
                exit(0);
36
            }
37 5
38 5
            \fclose($pair[1]);
39 5
40 5
            $children[$pid] = $pair[0];
41
        }
42 5
43
        while(-1 !== $pid = \pcntl_wait($status)) {
44 5
            $socket = $children[$pid];
45
46
            if ('' !== $response = \trim(\fgets($socket))) {
47
                $responses[] = $response;
48
            }
49
50
            \fclose($socket);
51
        }
52
53
        return empty($responses) ?
54 5
            null : \sprintf('[%s]', \implode(',', $responses));
55
    }
56
}
57