1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psonic; |
4
|
|
|
|
5
|
|
|
use Psonic\Exceptions\ConnectionException; |
6
|
|
|
use Psonic\Contracts\Client as ClientInterface; |
7
|
|
|
use Psonic\Contracts\Command as CommandInterface; |
8
|
|
|
use Psonic\Contracts\Response as ResponseInterface; |
9
|
|
|
|
10
|
|
|
class Client implements ClientInterface |
11
|
|
|
{ |
12
|
|
|
private $resource; |
13
|
|
|
|
14
|
|
|
private $host; |
15
|
|
|
private $port; |
16
|
|
|
private $errorNo; |
17
|
|
|
private $errorMessage; |
18
|
|
|
private $maxTimeout; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Client constructor. |
22
|
|
|
* @param string $host |
23
|
|
|
* @param int $port |
24
|
|
|
* @param int $timeout |
25
|
|
|
*/ |
26
|
|
|
public function __construct($host = 'localhost', $port = 1491, $timeout = 30) |
27
|
|
|
{ |
28
|
|
|
$this->host = $host; |
29
|
|
|
$this->port = $port; |
30
|
|
|
$this->maxTimeout = $timeout; |
31
|
|
|
$this->errorNo = null; |
32
|
|
|
$this->errorMessage = ''; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param CommandInterface $command |
37
|
|
|
* @return ResponseInterface |
38
|
|
|
* @throws ConnectionException |
39
|
|
|
*/ |
40
|
|
|
public function send(CommandInterface $command): ResponseInterface |
41
|
|
|
{ |
42
|
|
|
if (!$this->resource) { |
43
|
|
|
throw new ConnectionException(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
fwrite($this->resource, $command); |
47
|
|
|
return $this->read(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* reads the buffer from a given stream |
52
|
|
|
* @return ResponseInterface |
53
|
|
|
*/ |
54
|
|
|
public function read(): ResponseInterface |
55
|
|
|
{ |
56
|
|
|
$message = stream_get_line($this->resource, 2048, "\r\n"); |
57
|
|
|
return new SonicResponse($message); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @throws ConnectionException |
62
|
|
|
* connects to the socket |
63
|
|
|
*/ |
64
|
|
|
public function connect() |
65
|
|
|
{ |
66
|
|
|
if (!$this->resource = stream_socket_client("tcp://{$this->host}:{$this->port}", $this->errorNo, $this->errorMessage, $this->maxTimeout)) { |
67
|
|
|
throw new ConnectionException(); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Disconnects from a socket |
73
|
|
|
*/ |
74
|
|
|
public function disconnect() |
75
|
|
|
{ |
76
|
|
|
stream_socket_shutdown($this->resource, STREAM_SHUT_WR); |
77
|
|
|
$this->resource = null; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return bool |
82
|
|
|
* clears the output buffer |
83
|
|
|
*/ |
84
|
|
|
public function clearBuffer() |
85
|
|
|
{ |
86
|
|
|
stream_get_line($this->resource, 4096, "\r\n"); |
87
|
|
|
return true; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|