2018-11-21 11:13:40 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace BeyondCode\LaravelWebSockets\LaravelEcho\Pusher\Channels;
|
|
|
|
|
|
|
|
|
|
use Ratchet\ConnectionInterface;
|
|
|
|
|
|
|
|
|
|
class PresenceChannel extends Channel
|
|
|
|
|
{
|
|
|
|
|
protected $subscriptions = [];
|
|
|
|
|
|
2018-11-21 23:14:56 +00:00
|
|
|
/*
|
2018-11-21 11:14:45 +00:00
|
|
|
* @link https://pusher.com/docs/pusher_protocol#presence-channel-events
|
|
|
|
|
*/
|
2018-11-21 23:03:13 +00:00
|
|
|
public function subscribe(ConnectionInterface $connection, $payload)
|
2018-11-21 11:13:40 +00:00
|
|
|
{
|
2018-11-21 23:03:13 +00:00
|
|
|
$this->saveConnection($connection);
|
2018-11-21 14:42:04 +00:00
|
|
|
|
2018-11-21 11:13:40 +00:00
|
|
|
$channelData = json_decode($payload->channel_data);
|
2018-11-22 07:37:47 +00:00
|
|
|
$this->subscriptions[$connection->socketId] = $channelData;
|
2018-11-21 11:13:40 +00:00
|
|
|
|
|
|
|
|
// Send the success event
|
2018-11-21 23:03:13 +00:00
|
|
|
$connection->send(json_encode([
|
2018-11-21 11:13:40 +00:00
|
|
|
'event' => 'pusher_internal:subscription_succeeded',
|
|
|
|
|
'channel' => $this->channelId,
|
|
|
|
|
'data' => json_encode($this->getChannelData())
|
|
|
|
|
]));
|
2018-11-21 20:23:25 +00:00
|
|
|
|
2018-11-21 23:03:13 +00:00
|
|
|
$this->broadcastToOthers($connection, [
|
|
|
|
|
'event' => 'pusher_internal:member_added',
|
|
|
|
|
'channel' => $this->channelId,
|
|
|
|
|
'data' => json_encode($channelData)
|
|
|
|
|
]);
|
2018-11-21 11:13:40 +00:00
|
|
|
}
|
|
|
|
|
|
2018-11-21 21:36:50 +00:00
|
|
|
public function unsubscribe(ConnectionInterface $connection)
|
|
|
|
|
{
|
|
|
|
|
parent::unsubscribe($connection);
|
|
|
|
|
|
2018-11-22 07:37:47 +00:00
|
|
|
$this->broadcastToOthers($connection, [
|
|
|
|
|
'event' => 'pusher_internal:member_removed',
|
|
|
|
|
'channel' => $this->channelId,
|
|
|
|
|
'data' => json_encode([
|
|
|
|
|
'user_id' => $this->subscriptions[$connection->socketId]->user_id
|
|
|
|
|
])
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
unset($this->subscriptions[$connection->socketId]);
|
2018-11-21 21:36:50 +00:00
|
|
|
}
|
|
|
|
|
|
2018-11-21 23:14:56 +00:00
|
|
|
protected function getChannelData(): array
|
2018-11-21 11:13:40 +00:00
|
|
|
{
|
|
|
|
|
return [
|
|
|
|
|
'presence' => [
|
2018-11-22 07:37:47 +00:00
|
|
|
'ids' => array_map(function($channelData) { return $channelData->user_id; }, $this->subscriptions),
|
2018-11-21 11:13:40 +00:00
|
|
|
'hash' => array_map(function($channelData) { return $channelData->user_info; }, $this->subscriptions),
|
|
|
|
|
'count' => count($this->subscriptions)
|
|
|
|
|
]
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
}
|