Passed
Push — master ( b22a88...886da7 )
by Marcel
02:28
created

ConcurrentServer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 80.95%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
eloc 21
c 6
b 0
f 0
dl 0
loc 40
ccs 17
cts 21
cp 0.8095
rs 10
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
B batch() 0 38 6
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
final class ConcurrentServer extends Server
16
{
17 4
    protected function batch(Input $input): ?string
18
    {
19 4
        \assert($input->isArray());
20
21 4
        $children = [];
22 4
        $responses = [];
23 4
        foreach ($input->data() as $request) {
24 4
            $pair = \stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
25
26 4
            $pid = \pcntl_fork();
27
28 4
            if (0 === $pid) {
29
                \fclose($pair[0]);
30
31
                \fwrite($pair[1], $this->single(Input::fromSafeData($request)) . '');
32
33
                \fclose($pair[1]);
34
35
                exit(0);
36
            }
37
38 4
            \fclose($pair[1]);
39
40 4
            $children[$pid] = $pair[0];
41
        }
42
43 4
        while (-1 !== $pid = \pcntl_wait($status)) {
44 4
            $socket = $children[$pid];
45
46 4
            if ('' !== $response = \stream_get_contents($socket)) {
47 3
                $responses[] = $response;
48
            }
49
50 4
            \fclose($socket);
51
        }
52
53 4
        return empty($responses) ?
54 4
            null : \sprintf('[%s]', \implode(',', $responses));
55
    }
56
}
57