-
Notifications
You must be signed in to change notification settings - Fork 5
/
RedisBroadcaster.php
87 lines (74 loc) · 2.14 KB
/
RedisBroadcaster.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
<?php
namespace mkiselev\broadcasting\broadcasters;
use mkiselev\broadcasting\helpers\StrHelper;
use yii\di\Instance;
use yii\helpers\ArrayHelper;
use yii\redis\Connection;
use yii\web\ForbiddenHttpException;
class RedisBroadcaster extends Broadcaster
{
/**
* The Redis connection
*
* @var \yii\redis\Connection
*/
public $redis = 'redis';
public function init()
{
$this->redis = Instance::ensure($this->redis);
}
/**
* Authenticate the incoming request for a given channel.
*
* @param \yii\web\User $user
* @param string $channelName
* @return mixed
* @throws \yii\web\ForbiddenHttpException
*/
public function auth($user, $channelName)
{
if (StrHelper::startsWith($channelName, ['private-', 'presence-']) && $user->isGuest) {
throw new ForbiddenHttpException();
}
$channelName = StrHelper::startsWith($channelName, 'private-')
? StrHelper::replaceFirst('private-', '', $channelName)
: StrHelper::replaceFirst('presence-', '', $channelName);
return parent::verifyUserCanAccessChannel($user, $channelName);
}
/**
* Return the valid authentication response.
*
* @param \yii\web\User $user
* @param mixed $result
* @return mixed
*/
public function validAuthenticationResponse($user, $result)
{
if (is_bool($result)) {
return json_encode($result);
}
return json_encode(['channel_data' => [
'user_id' => $user->id,
'user_info' => $result,
]]);
}
/**
* Broadcast the given event.
*
* @param array $channels
* @param string $event
* @param array $payload
* @return void
*/
public function broadcast(array $channels, $event, array $payload = [])
{
$payload = json_encode([
'event' => $event,
'data' => $payload,
'socket' => ArrayHelper::remove($payload, 'socket'),
]);
foreach ($this->formatChannels($channels) as $channel) {
$this->redis->publish($channel, $payload);
}
}
}