forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.php
98 lines (83 loc) · 2.51 KB
/
Client.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
<?php
namespace PHPPM;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use React\Socket\Connection;
class Client
{
use ProcessCommunicationTrait;
/**
* @var int
*/
protected $controllerPort;
/**
* @var LoopInterface
*/
protected $loop;
/**
* @var Connection
*/
protected $connection;
public function __construct($controllerPort = 5500)
{
$this->controllerPort = $controllerPort;
$this->loop = Factory::create();
}
/**
* @return Connection
*/
protected function getConnection()
{
if ($this->connection) {
$this->connection->close();
unset($this->connection);
}
$client = stream_socket_client($this->getControllerSocket());
$this->connection = new Connection($client, $this->loop);
return $this->connection;
}
protected function request($command, $options, $callback)
{
$data['cmd'] = $command;
$data['options'] = $options;
$connection = $this->getConnection();
$result = '';
$connection->on('data', function($data) use (&$result) {
$result .= $data;
});
$connection->on('close', function() use ($callback, &$result) {
$callback($result);
});
$connection->write(json_encode($data) . PHP_EOL);
}
public function getStatus(callable $callback)
{
$this->request('status', [], function($result) use ($callback) {
$callback(json_decode($result, true));
});
$this->loop->run();
}
/**
* @return string
*/
protected function getControllerSocket()
{
$host = $this->getNewControllerHost(false);
$port = $this->controllerPort;
$localSocket = '';
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$localSocket = 'tcp://' . $host . ':' . $port;
} elseif (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
// enclose IPv6 addresses in square brackets before appending port
$localSocket = 'tcp://[' . $host . ']:' . $port;
} elseif (preg_match('#^unix://#', $host)) {
$localSocket = $host;
} else {
throw new \UnexpectedValueException(
'"' . $host . '" does not match to a set of supported transports. ' .
'Supported transports are: IPv4, IPv6 and unix:// .'
, 1433253311);
}
return $localSocket;
}
}