-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDriver.php
113 lines (96 loc) · 2.24 KB
/
Driver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace SlowDB;
/**
* Driver Class
*
* @author Keith Kirk <keith@kmfk.io>
*/
class Driver
{
/**
* The driver
*
* @var string
*/
const CLIENT = 'php-library';
/**
* Database server host
*
* @var string
*/
private $host;
/**
* Database server port
*
* @var string
*/
private $port;
/**
* The collection name
*
* @var string
*/
private $collection;
/**
* Constructor
*
* @param string $host The database host
* @param string $port The database port
*/
public function __construct($host, $port)
{
$this->host = $host;
$this->port = $port;
}
/**
* Magic method that sets the collection name for a Command
*
* @param string $name The collection name
*
* @return self
*/
public function __get($name)
{
$this->collection = $name;
return $this;
}
/**
* Sends Commands to the Database Server
*
* @param string $method The method/command to call
* @param array $arguments An array of arguments for the command
*
* @return mixed
*/
public function __call($method, array $arguments = [])
{
$connection = $this->buildConnection();
$command = [
'client' => self::CLIENT,
'method' => $method,
'arguments' => $arguments
];
if (isset($this->collection)) {
$command['collection'] = $this->collection;
$this->collection = null;
}
fwrite($connection, json_encode($command));
$response = stream_get_contents($connection);
fclose($connection);
return json_decode($response, true);
}
/**
* Builds and tests the connection to the Database
*
* @return resource
*/
private function buildConnection()
{
$connection = stream_socket_client("tcp://{$this->host}:{$this->port}", $errno, $message);
$success = fread($connection, 26);
if (false === $connection || false === $success) {
throw new \UnexpectedValueException("Failed to connect: $message");
}
return $connection;
}
}