forked from php-pm/php-pm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProcessCommunicationTrait.php
74 lines (65 loc) · 1.91 KB
/
ProcessCommunicationTrait.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
<?php
namespace PHPPM;
use React\Socket\Connection;
/**
* Little trait used in ProcessManager and ProcessSlave to have a simple json process communication.
*/
trait ProcessCommunicationTrait
{
/**
* Parses a received message. Redirects to the appropriate `command*` method.
*
* @param array $data
* @param Connection $conn
*
* @throws \Exception when invalid 'cmd' in $data.
*/
public function processMessage($data, Connection $conn)
{
$array = json_decode($data, true);
$method = 'command' . ucfirst($array['cmd']);
if (is_callable(array($this, $method))) {
$this->$method($array, $conn);
} else {
throw new \Exception(sprintf('Command %s not found. Got %s', $method, $data));
}
}
/**
* Binds data-listener to $conn and waits for incoming commands.
*
* @param Connection $conn
*/
protected function bindProcessMessage(Connection $conn)
{
$buffer = '';
$conn->on(
'data',
\Closure::bind(
function ($data) use ($conn, &$buffer) {
$buffer .= $data;
if (substr($buffer, -1) === PHP_EOL) {
foreach (explode(PHP_EOL, $buffer) as $message) {
if ($message) {
$this->processMessage($message, $conn);
}
}
$buffer = '';
}
},
$this
)
);
}
/**
* Sends a message through $conn.
*
* @param Connection $conn
* @param string $command
* @param array $message
*/
protected function sendMessage(Connection $conn, $command, array $message = [])
{
$message['cmd'] = $command;
$conn->write(json_encode($message) . PHP_EOL);
}
}