Completed
Push — master ( 0f4882...0b6865 )
by Roberto
03:52
created

Connection::createSocket()   A

Complexity

Conditions 1
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 2
nop 0
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace RedMoon\TinkerServer;
4
5
class Connection
6
{
7
    protected $socket;
8
9
    protected $host;
10
11
    public function __construct($host)
12
    {
13
        $this->host = $host;
14
    }
15
16
    public function write(array $namedParameters): bool
17
    {
18
        if (! $this->socket = $this->socket ?: $this->createSocket()) {
19
            return false;
20
        }
21
22
        set_error_handler([self::class, 'nullErrorHandler']);
23
24
        try {
25
            $encodedPayload = base64_encode(serialize($namedParameters))."\n";
26
27
            if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) {
28
                return true;
29
            }
30
31
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
32
            fclose($this->socket);
33
            $this->socket = $this->createSocket();
34
35
            if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) {
36
                return true;
37
            }
38
        } finally {
39
            restore_error_handler();
40
        }
41
42
        return false;
43
    }
44
45
    private static function nullErrorHandler($t, $m)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
Unused Code introduced by
The parameter $t is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $m is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46
    {
47
        // no-op
48
    }
49
50
    private function createSocket()
51
    {
52
        set_error_handler([self::class, 'nullErrorHandler']);
53
        try {
54
            return stream_socket_client($this->host, $errno, $errstr, 3, STREAM_CLIENT_CONNECT);
55
        } finally {
56
            restore_error_handler();
57
        }
58
    }
59
}
60