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

SocketFactory::needMoreThanOne()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\React;
6
7
use Assert\Assertion;
8
use Psr\Container\ContainerInterface;
9
use React\EventLoop\LoopInterface;
10
use React\Socket\Server as Socket;
11
12
class SocketFactory
13
{
14
    private const DEFAULT_TCP_CONFIG = ['tcp' => ['so_reuseport' => false]];
15
    private const REUSE_PORT = true;
16
    private const DEFAULT_WORKERS_NUMBER = 1;
17
18 7
    public function __invoke(ContainerInterface $container): Socket
19
    {
20
        /** @var LoopInterface $loop */
21 7
        $loop = $container->get(LoopInterface::class);
22
        /** @var array<string, array> $globalConfig */
23 7
        $globalConfig = $container->get('config');
24
        /** @var array<string, string|null> $config */
25 7
        $config = $globalConfig['server'];
26 7
        Assertion::notEmptyKey($config, 'host');
27 6
        Assertion::notEmptyKey($config, 'port');
28 5
        Assertion::keyExists($config, 'workers');
29
        /** @var string $host */
30 4
        $host = $config['host'];
31 4
        Assertion::ipv4($host);
32
        /** @var int $port */
33 3
        $port = $config['port'];
34 3
        Assertion::integer($port);
35
        /** @var int $workersNumber */
36 2
        $workersNumber = $config['workers'];
37 2
        Assertion::integer($workersNumber);
38 1
        $tcpConfig = self::DEFAULT_TCP_CONFIG;
39 1
        if ($this->needMoreThanOne($workersNumber)) {
40
            $tcpConfig['tcp']['so_reuseport'] = self::REUSE_PORT;
41
        }
42
43 1
        return new Socket(sprintf('%s:%s', $host, $port), $loop, $tcpConfig);
44
    }
45
46 1
    private function needMoreThanOne(int $workersNumber): bool
47
    {
48 1
        return self::DEFAULT_WORKERS_NUMBER < $workersNumber;
49
    }
50
}
51