Completed
Push — master ( 99ae35...96bc9a )
by Renato
10:36
created

WebSocket::factory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
namespace SocketCluster;
3
4
use WebSocket\Client;
5
6
class WebSocket
7
{
8
    /**
9
     * Get Client
10
     *
11
     * @return Client
12
     */
13
    public static function factory($options)
14
    {
15
        $socket_uri = self::parseOptions($options);
16
17
        return new Client($socket_uri);
18
    }
19
20
    /**
21
     * Parse Options
22
     *
23
     * @param string|array $options
24
     *
25
     * @return void
26
     */
27
    protected static function parseOptions($options)
28
    {
29
        if (!is_array($options)) {
30
            $options = parse_url($options);
31
        }
32
33
        $default = ['scheme'=>'', 'host'=>'', 'port'=>'', 'path'=>'', 'query'=>[], 'fragment'=>''];
34
        $options = array_merge($default, $options);
35
36
        if (isset($options['secure'])) {
37
            $scheme = ((bool) $options['secure']) ? 'wss' : 'ws';
38
39
        } else {
40
            $scheme = (in_array($options['scheme'], ['wss', 'https'])) ? 'wss' : 'ws';
41
        }
42
43
        $query = $options['query'];
44
        if (!is_array($query)) {
45
            parse_str($options['query'], $query);
46
        }
47
48
        $host = trim($options['host'], "/");
49
        $port = !empty($options['port']) ? ":".$options['port'] : '';
50
        $path = trim($options['path'], "/");
51
        $path = !empty($path) ? $path."/" : '';
52
        $query = count($query) ? '?'.http_build_query($query) : '';
53
54
        return sprintf("%s://%s%s/%s%s", $scheme, $host, $port, $path, $query);
55
    }
56
}
57