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

Relay::create()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 6
nop 1
dl 0
loc 29
rs 8.2114
c 0
b 0
f 0
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