-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.php
88 lines (76 loc) · 2.44 KB
/
monitor.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
<?php
/**
* Use this script, when developing, by running it, to automatically restart
* the server when ever a file has changed within the project.
*/
require 'vendor/autoload.php';
use React\EventLoop\Factory;
use MKraemer\ReactInotify\Inotify;
use Christiaan\StreamProcess\StreamProcess;
// Number of seconds to delay reloading for, allows mass file operations
// to continue without triggering a large number of reloads.
const DELAY = 0.5;
// The PHP interpreter to execute scripts with, defaults to the current
// interpreter, could be used to start another, such as HHVM.
const INTERPRETER = PHP_BINARY;
// The ReactPHP script you want to invoke.
const SCRIPT = 'server.php';
$loop = Factory::create();
$message = function($data) {
echo date('[H:i:s] '), $data;
};
$forward = function($stream) {
$data = fgets($stream);
$delimiter = "\n > ";
if ($data == null) return;
echo date('[H:i:s] > '), implode($delimiter, explode("\n", rtrim($data))), "\n";
};
$stop = function() use ($loop, $message, &$process) {
if ($process instanceof StreamProcess) {
$message("Stopping process... ");
$loop->removeReadStream($process->getReadStream());
$loop->removeReadStream($process->getErrorStream());
$process->terminate();
$process->close();
echo "done.\n";
}
};
$start = function() use ($loop, $message, $forward, &$process, &$time) {
$message("Starting process... ");
$command = INTERPRETER . ' ' . escapeshellarg(realpath(SCRIPT));
$process = new StreamProcess($command);
echo "done.\n";
$loop->addReadStream($process->getReadStream(), $forward);
$loop->addReadStream($process->getErrorStream(), $forward);
if (isset($time) === false) {
$time = microtime(true);
}
};
$restart = function() use ($loop, $stop, $start, &$time) {
$now = microtime(true);
if ($now <= $time) {
return;
}
$stop();
$start();
$time = microtime(true) + DELAY;
};
$exit = function() use ($loop, $stop) {
$stop();
$loop->stop();
exit;
};
// Begin monitoring:
$inotify = new Inotify($loop);
$inotify->add(__DIR__, IN_CLOSE_WRITE | IN_CREATE | IN_DELETE);
$inotify->add(__DIR__ . '/app', IN_CLOSE_WRITE | IN_CREATE | IN_DELETE);
$inotify->add(__DIR__ . '/src', IN_CLOSE_WRITE | IN_CREATE | IN_DELETE);
$inotify->on(IN_CLOSE_WRITE, $restart);
$inotify->on(IN_CREATE, $restart);
$inotify->on(IN_DELETE, $restart);
// Wait for exit signal:
$pcntl = new MKraemer\ReactPCNTL\PCNTL($loop);
$pcntl->on(SIGTERM, $exit);
$pcntl->on(SIGINT, $exit);
$start();
$loop->run();