forked from dizews/yii2-push-stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PushStreamWidget.php
66 lines (57 loc) · 1.8 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
<?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';
public function init()
{
$config = \Yii::$app->get($this->pusher)->listenServerOptions;
$this->pluginOptions = ArrayHelper::merge([
'jsonTextKey' => 'body',
'useSsl' => $config['useSsl'],
'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);
$channels = '';
foreach ((array)$this->channels as $channel) {
$channels .= $this->pusher .".addChannel('{$channel}');";
}
$debug = \Yii::$app->get($this->pusher)->debug ? "PushStream.LOG_LEVEL = 'debug';" : '';
$js = <<<JS
$debug;
var {$this->pusher} = new PushStream($options);
{$channels}
{$this->pusher}.onmessage = function (text, id, channel, eventId, time) {
$('#{$this->containerId}').trigger({
channel: channel,
type: eventId,
body: text,
time: time,
});
};
JS;
if ($this->connect) {
$js .= $this->pusher .'.connect();';
}
$view->registerJs($js);
}
}