Passed
Push — github_action ( b6fb67 )
by Koldo
03:40
created

SocketFactory   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
eloc 21
c 2
b 0
f 0
dl 0
loc 37
ccs 18
cts 19
cp 0.9474
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 26 2
A needMoreThanOne() 0 3 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