Node   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 68
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 3
A getConnection() 0 12 3
A getOptions() 0 3 1
1
<?php
2
namespace evseevnn\Cassandra\Cluster;
3
4
use evseevnn\Cassandra\Exception\ConnectionException;
5
6
class Node {
7
8
	const STREAM_TIMEOUT = 10;
9
10
	/**
11
	 * @var string
12
	 */
13
	private $host;
14
15
	/**
16
	 * @var int
17
	 */
18
	private $port = 9042;
19
20
	/**
21
	 * @var resource
22
	 */
23
	private $socket;
24
25
	/**
26
	 * @var array
27
	 */
28
	private $options = [
29
		'username' => null,
30
		'password' => null
31
	];
32
33
	/**
34
	 * @param string $host
35
	 * @param array $options
36
	 * @throws \InvalidArgumentException
37
	 */
38
	public function __construct($host, array $options = []) {
39
		$this->host = $host;
40
		if (strstr($this->host, ':')) {
41
			$this->port = (int)substr(strstr($this->host, ':'), 1);
42
			$this->host = substr($this->host, 0, -1 - strlen($this->port));
43
			if (!$this->port) {
44
				throw new \InvalidArgumentException('Invalid port number');
45
			}
46
		}
47
		$this->options = array_merge($this->options, $options);
48
	}
49
50
	/**
51
	 * @return resource
52
	 * @throws \Exception
53
	 */
54
	public function getConnection() {
55
		if (!empty($this->socket)) return $this->socket;
56
57
		$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
58
		socket_set_option($this->socket, getprotobyname('TCP'), TCP_NODELAY, 1);
59
		socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, ["sec" => self::STREAM_TIMEOUT, "usec" => 0]);
60
		if (!socket_connect($this->socket, $this->host, $this->port)) {
61
			throw new ConnectionException("Unable to connect to Cassandra node: {$this->host}:{$this->port}");
62
		}
63
64
		return $this->socket;
65
	}
66
67
	/**
68
	 * @return array
69
	 */
70
	public function getOptions() {
71
		return $this->options;
72
	}
73
}