-
Notifications
You must be signed in to change notification settings - Fork 2
/
PushStreamWidget.php
74 lines (59 loc) · 1.81 KB
/
PushStreamWidget.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 dizews\pushStream;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
class PushStreamWidget extends Widget
{
public $pluginOptions = [];
public $channels;
public $pusher = 'pusher';
public $connect = true;
public $containerId = 'push-stream-events';
private $url;
public function init()
{
$config = array_merge($this->getPusher()->serverOptions, $this->getPusher()->listenServerOptions);
$this->url = "{$config['host']}{$config['path']}";
$this->pluginOptions = ArrayHelper::merge([
'host' => $config['host'],
'port' => $config['port'],
'modes' => $config['modes'],
], $this->pluginOptions);
}
/**
* @inheritdoc
*/
public function run()
{
echo Html::tag('div', null, ['id' => $this->containerId, 'style'=> 'display:none']);
$view = $this->getView();
PushStreamAsset::register($view);
$options = Json::encode($this->pluginOptions);
$url = $this->url.'/'.implode('/', $this->channels);
$js= <<<JS
var {$this->pusher} = new NchanSubscriber('{$url}', {$options});
{$this->pusher}.on("message", function(event, message_metadata) {
var msg = jQuery.parseJSON(event);
$('#{$this->containerId}').trigger({
channel: msg.channel,
type: msg.eventId,
body: msg.payload,
time: msg.time
});
});
JS;
if ($this->connect) {
$js .= $this->pusher .'.start();';
}
$view->registerJs($js);
}
/**
* @return Pusher
*/
private function getPusher()
{
return Yii::$app->get($this->pusher);
}
}