laravel-websockets/src/WebSocket/Pusher/Channels/PresenceChannel.php

80 lines
2.2 KiB
PHP
Raw Normal View History

2018-11-21 11:13:40 +00:00
<?php
2018-11-27 15:07:29 +00:00
namespace BeyondCode\LaravelWebSockets\WebSocket\Pusher\Channels;
2018-11-21 11:13:40 +00:00
use Ratchet\ConnectionInterface;
2018-11-26 23:07:35 +00:00
use stdClass;
2018-11-21 11:13:40 +00:00
class PresenceChannel extends Channel
{
2018-11-22 21:02:36 +00:00
protected $users = [];
2018-11-21 11:13:40 +00:00
2018-11-22 21:09:32 +00:00
public function getUsers(): array
{
return $this->users;
}
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-26 23:07:35 +00:00
public function subscribe(ConnectionInterface $connection, stdClass $payload)
2018-11-21 11:13:40 +00:00
{
2018-11-22 09:54:51 +00:00
$this->verifySignature($connection, $payload);
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-27 09:55:46 +00:00
$this->users[$channelData->user_id] = $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([
2018-11-22 21:02:36 +00:00
'user_id' => $this->users[$connection->socketId]->user_id
2018-11-22 07:37:47 +00:00
])
]);
2018-11-22 21:02:36 +00:00
unset($this->users[$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
{
2018-11-27 09:55:46 +00:00
$hash = [];
foreach ($this->users as $socketId => $channelData) {
$hash[$channelData->user_id] = $channelData->user_info;
}
2018-11-21 11:13:40 +00:00
return [
'presence' => [
2018-11-27 09:55:46 +00:00
'ids' => array_values(array_map(function($channelData) { return (string)$channelData->user_id; }, $this->users)),
'hash' => $hash,
2018-11-22 21:02:36 +00:00
'count' => count($this->users)
2018-11-21 11:13:40 +00:00
]
];
}
2018-11-22 21:02:36 +00:00
public function toArray(): array
{
return array_merge(parent::toArray(),[
'user_count' => count($this->users),
]);
}
2018-11-21 11:13:40 +00:00
}