Passed
Push — drift_server ( 5c2da8...258843 )
by Koldo
12:53
created

Child::fork()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 29
ccs 0
cts 16
cp 0
rs 9.4555
cc 5
nc 5
nop 3
crap 30
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\React;
6
7
use RuntimeException;
8
use function pcntl_fork;
9
use function pcntl_waitpid;
10
11
class Child
12
{
13
    private const DEFAULT_NUMBER_OF_FORKS = 0;
14
15
    public static function fork(
16
        int $numberOfWorkers,
17
        callable $asyncServer,
18
        int $numberOfFork = self::DEFAULT_NUMBER_OF_FORKS
19
    ): int {
20
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
21
            throw new RuntimeException('The PHP pcntl extension is not available for Windows systems');
22
        }
23
24
        $pid = pcntl_fork();
25
        if (-1 === $pid) {
26
            throw new RuntimeException('Fork Failed');
27
        }
28
29
        if (0 === $pid) {
30
            $asyncServer();
31
            pcntl_waitpid($pid, $status);
32
            return $pid;
33
        }
34
35
        // @parent
36
        $numberOfWorkers--;
37
        ++$numberOfFork;
38
        if (self::DEFAULT_NUMBER_OF_FORKS < $numberOfWorkers) {
39
            self::fork($numberOfWorkers, $asyncServer, $numberOfFork);
40
        }
41
42
        pcntl_waitpid($pid, $status);
43
        return $pid;
44
    }
45
}
46