SocketTrait   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 20
c 2
b 0
f 0
dl 0
loc 72
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getError() 0 8 1
A close() 0 3 1
A create() 0 5 1
A connect() 0 18 4
1
<?php
2
namespace Health\Checks\Traits;
3
4
/**
5
 * Socket operations
6
 */
7
trait SocketTrait
8
{
9
10
    /**
11
     * Socket resource
12
     *
13
     * @var resource
14
     */
15
    protected $resource = null;
16
17
    /**
18
     *
19
     * @param int $domain
20
     * @param int $type
21
     * @param int $protocol
22
     *
23
     * @return resource
24
     */
25
    protected function create($domain, $type, $protocol)
26
    {
27
        $this->resource = @socket_create($domain, $type, $protocol);
28
29
        return $this->resource;
30
    }
31
32
    /**
33
     * Connect to address
34
     *
35
     * @param string $address
36
     * @param int|null $timeout
37
     * @return boolean
38
     */
39
    protected function connect($address)
40
    {
41
        if (filter_var($address, FILTER_VALIDATE_IP) || preg_match("/:/", $address)) {
42
            if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
43
                $address = 'http://' . $address;
44
            }
45
46
            $url = parse_url($address);
47
48
            $host = $url['host'] ?? null;
49
            $port = $url['port'] ?? null;
50
        } else {
51
            // For UNIX sockets
52
            $host = $address;
53
            $port = null;
54
        }
55
56
        return @socket_connect($this->resource, $host, $port);
57
    }
58
59
    /**
60
     * Close SocketTrait
61
     */
62
    protected function close()
63
    {
64
        socket_close($this->resource);
65
    }
66
67
    /**
68
     *
69
     * @return array
70
     */
71
    protected function getError()
72
    {
73
        $code = socket_last_error();
74
        $msg = socket_strerror($code);
75
76
        return [
77
            'code' => $code,
78
            'message' => $msg
79
        ];
80
    }
81
}
82