forked from gonzalo123/nov-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNovComet.php
executable file
·83 lines (74 loc) · 2.17 KB
/
NovComet.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
<?php
/**
* Lazy Comet with PHP (publisher and subscriber)
*
* THIS PROGRAM COMES WITH ABSOLUTELY NO WARANTIES !
* USE IT AT YOUR OWN RISKS !
*
* @author Gonzalo Ayuso <[email protected]>
* @copyright under GPL 2 licence
*/
class NovComet {
const COMET_OK = 0;
const COMET_CHANGED = 1;
private $_tries;
private $_var;
private $_sleep;
private $_ids = array();
private $_callback = null;
public function __construct($tries = 10, $sleep = 2)
{
$this->_tries = $tries;
$this->_sleep = $sleep;
}
public function setVar($key, $value)
{
$this->_vars[$key] = $value;
}
public function setTries($tries)
{
$this->_tries = $tries;
}
public function setSleepTime($sleep)
{
$this->_sleep = $sleep;
}
public function setCallbackCheck($callback)
{
$this->_callback = $callback;
}
const DEFAULT_COMET_PATH = "/dev/shm/%s.comet";
public function run() {
if (is_null($this->_callback)) {
$defaultCometPAth = self::DEFAULT_COMET_PATH;
$callback = function($id) use ($defaultCometPAth) {
$cometFile = sprintf($defaultCometPAth, $id);
return (is_file($cometFile)) ? filemtime($cometFile) : 0;
};
} else {
$callback = $this->_callback;
}
$out = array();
for ($i = 0; $i < $this->_tries; $i++) {
foreach ($this->_vars as $id => $timestamp) {
if ((integer) $timestamp == 0) {
$timestamp = time();
}
$fileTimestamp = $callback($id);
if ($fileTimestamp > $timestamp) {
$out[$id] = $fileTimestamp;
}
clearstatcache();
}
if (count($out) > 0) {
return json_encode(array('s' => self::COMET_CHANGED, 'k' => $out));
}
sleep($this->_sleep);
}
return json_encode(array('s' => self::COMET_OK));
}
public function publish($id)
{
return json_encode(touch(sprintf(self::DEFAULT_COMET_PATH, $id)));
}
}