Completed
Push — master ( 8abb4e...24d969 )
by Daniel
02:20
created

SocketClient::isConnected()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
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 42
    public function __construct(string $socketUri, int $timeout = 30)
24
    {
25 42
        $this->socketUri = $socketUri;
26 42
        $this->timeout = $timeout;
27 42
    }
28
29 36
    public function connect(): self
30
    {
31 36
        $fp = @stream_socket_client($this->socketUri, $errno, $errstr, $this->timeout);
32 36
        if (!is_resource($fp) && false === $fp) {
33 2
            $message = sprintf("Stream Connection Failed: %s unable to connect to %s", $errstr, $this->socketUri);
34 2
            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 42
    public function disconnect(): self
66
    {
67 42
        if (!is_null($this->socket)) {
68 34
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
69 34
            fclose($this->socket);
70
        }
71 42
        $this->socket = null;
72 42
        $this->connected = false;
73
74 42
        return $this;
75
    }
76
77 22
    public function __destruct()
78
    {
79 22
        $this->disconnect();
80 22
    }
81
}
82