Passed
Push — master ( 183954...8abb4e )
by Daniel
02:22
created

SocketClient::setSocketUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
namespace MallardDuck\Whois;
4
5
use MallardDuck\Whois\Exceptions\SocketClientException;
6
7
/**
8
 * A simple socket stream client.
9
 *
10
 * @author mallardduck <[email protected]>
11
 *
12
 * @copyright lucidinternets.com 2020
13
 *
14
 * @version ?.?.?
15
 */
16
final class SocketClient
17
{
18
    protected $socketUri = null;
19
    protected $socket = null;
20
    protected $timeout = 30;
21
    protected $connected = false;
22
23 40
    public function __construct(string $socketUri, int $timeout = 30)
24
    {
25 40
        $this->socketUri = $socketUri;
26 40
        $this->timeout = $timeout;
27 40
    }
28
29 34
    public function connect(): self
30
    {
31 34
        $fp = stream_socket_client($this->socketUri, $errno, $errstr, $this->timeout);
32 34
        if (!is_resource($fp) && false === $fp) {
33
            $message = sprintf("Stream Connection Failed: %s", $errstr);
34
            throw new SocketClientException($message, $errno);
35
        }
36
37 34
        $this->socket = $fp;
38 34
        $this->connected = true;
39 34
        return $this;
40
    }
41
42 2
    public function isConnected(): bool
43
    {
44 2
        return $this->connected;
45
    }
46
47 34
    public function writeString(string $string)
48
    {
49 34
        if (!$this->connected) {
50 2
            $message = sprintf("The calling method %s requires the socket to be connected", __FUNCTION__);
51 2
            throw new SocketClientException($message);
52
        }
53 32
        return stream_socket_sendto($this->socket, $string);
54
    }
55
56 32
    public function readAll(): string
57
    {
58 32
        if (!$this->connected) {
59 2
            $message = sprintf("The calling method %s requires the socket to be connected", __FUNCTION__);
60 2
            throw new SocketClientException($message);
61
        }
62 30
        return stream_get_contents($this->socket);
63
    }
64
65 40
    public function disconnect(): self
66
    {
67 40
        if (!is_null($this->socket)) {
68 34
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
69 34
            fclose($this->socket);
70
        }
71 40
        $this->socket = null;
72 40
        $this->connected = false;
73
74 40
        return $this;
75
    }
76
77 20
    public function __destruct()
78
    {
79 20
        $this->disconnect();
80 20
    }
81
}
82