Completed
Push — master ( ea4653...e749a0 )
by
unknown
01:37 queued 11s
created

Relay   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 10
c 0
b 0
f 0
wmc 8
lcom 0
cbo 3

1 Method

Rating   Name   Duplication   Size   Complexity  
B create() 0 29 8
1
<?php
2
/**
3
 * Dead simple, high performance, drop-in bridge to Golang RPC with zero dependencies
4
 *
5
 * @author Valentin V
6
 */
7
8
namespace Spiral\Goridge;
9
10
abstract class Relay
11
{
12
    public const TCP_SOCKET  = 'tcp';
13
    public const UNIX_SOCKET = 'unix';
14
    public const STREAM      = 'pipes';
15
16
    private const CONNECTION = '/(?P<protocol>[^:\/]+):\/\/(?P<arg1>[^:]+)(:(?P<arg2>[^:]+))?/';
17
18
    public static function create(string $connection): RelayInterface
19
    {
20
        if (!preg_match(self::CONNECTION, strtolower($connection), $match)) {
21
            throw new Exceptions\RelayFactoryException('unsupported connection format');
22
        }
23
24
        switch ($match['protocol']) {
25
            case self::TCP_SOCKET:
26
                //fall through
27
            case self::UNIX_SOCKET:
28
                return new SocketRelay(
29
                    $match['arg1'],
30
                    isset($match['arg2']) ? (int)$match['arg2'] : null,
31
                    $match['protocol'] === self::TCP_SOCKET ? SocketRelay::SOCK_TCP : SocketRelay::SOCK_UNIX
32
                );
33
34
            case self::STREAM:
35
                if (!isset($match['arg2'])) {
36
                    throw new Exceptions\RelayFactoryException('unsupported stream connection format');
37
                }
38
39
                return new StreamRelay(
40
                    fopen("php://{$match['arg1']}", 'rb'),
41
                    fopen("php://{$match['arg2']}", 'wb')
42
                );
43
            default:
44
                throw new Exceptions\RelayFactoryException('unknown connection protocol');
45
        }
46
    }
47
}
48