Socket::close()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 0
1
<?php
2
3
namespace Vados\TCPLogger\socket;
4
5
/**
6
 * Class Socket
7
 * @package Vados\TCPLogger\socket
8
 */
9
abstract class Socket
10
{
11
    /**
12
     * @var string
13
     */
14
    private $host;
15
16
    /**
17
     * @var int
18
     */
19
    private $port;
20
21
    /**
22
     * @var resource
23
     */
24
    protected $socket;
25
26
    /**
27
     * Socket constructor.
28
     * @param string $host
29
     * @param int $port
30
     */
31
    public function __construct(string $host, int $port)
32
    {
33
        $this->host = $host;
34
        $this->port = $port;
35
    }
36
37
    /**
38
     * @return void
39
     */
40
    abstract public function initialize();
41
42
    /**
43
     * @return bool
44
     */
45
    private function connect(): bool
46
    {
47
        return socket_connect($this->socket, $this->host, $this->port);
48
    }
49
50
    /**
51
     * @param string $message
52
     * @return int
53
     */
54
    public function send(string $message): int
55
    {
56
        if ($this->socket === null) {
57
            $this->initialize();
58
            $this->connect();
59
        }
60
        return socket_send($this->socket, $message, strlen($message), 0);
61
    }
62
63
    /**
64
     * @return bool
65
     */
66
    public function close(): bool
67
    {
68
        if ($this->socket !== null && is_resource($this->socket)) {
69
            socket_close($this->socket);
70
        }
71
        return true;
72
    }
73
}