2018-11-21 11:13:40 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace BeyondCode\LaravelWebSockets\LaravelEcho\Pusher\Channels;
|
|
|
|
|
|
2018-11-21 14:42:04 +00:00
|
|
|
use Illuminate\Support\Collection;
|
2018-11-21 11:13:40 +00:00
|
|
|
use Ratchet\ConnectionInterface;
|
|
|
|
|
|
|
|
|
|
class Channel
|
|
|
|
|
{
|
2018-11-21 21:11:44 +00:00
|
|
|
/** @var string */
|
2018-11-21 11:13:40 +00:00
|
|
|
protected $channelId;
|
|
|
|
|
|
2018-11-21 14:42:04 +00:00
|
|
|
/** @var ConnectionInterface[] */
|
|
|
|
|
protected $connections = [];
|
2018-11-21 11:13:40 +00:00
|
|
|
|
2018-11-21 21:11:44 +00:00
|
|
|
public function __construct(string $channelId)
|
2018-11-21 11:13:40 +00:00
|
|
|
{
|
|
|
|
|
$this->channelId = $channelId;
|
|
|
|
|
}
|
|
|
|
|
|
2018-11-21 21:36:50 +00:00
|
|
|
public function hasConnections(): bool
|
|
|
|
|
{
|
|
|
|
|
return count($this->connections) > 0;
|
|
|
|
|
}
|
|
|
|
|
|
2018-11-21 14:42:04 +00:00
|
|
|
/**
|
|
|
|
|
* @link https://pusher.com/docs/pusher_protocol#presence-channel-events
|
|
|
|
|
*
|
|
|
|
|
* @param ConnectionInterface $conn
|
|
|
|
|
* @param $payload
|
|
|
|
|
*/
|
2018-11-21 11:13:40 +00:00
|
|
|
public function subscribe(ConnectionInterface $conn, $payload)
|
|
|
|
|
{
|
2018-11-21 14:42:04 +00:00
|
|
|
$this->saveConnection($conn);
|
2018-11-21 11:13:40 +00:00
|
|
|
|
2018-11-21 14:42:04 +00:00
|
|
|
// Send the success event
|
|
|
|
|
$conn->send(json_encode([
|
|
|
|
|
'event' => 'pusher_internal:subscription_succeeded',
|
|
|
|
|
'channel' => $this->channelId
|
|
|
|
|
]));
|
|
|
|
|
}
|
|
|
|
|
|
2018-11-21 21:36:50 +00:00
|
|
|
public function unsubscribe(ConnectionInterface $connection)
|
|
|
|
|
{
|
|
|
|
|
unset($this->connections[$connection->socketId]);
|
|
|
|
|
}
|
|
|
|
|
|
2018-11-21 14:42:04 +00:00
|
|
|
protected function saveConnection(ConnectionInterface $conn)
|
|
|
|
|
{
|
|
|
|
|
$this->connections[$conn->socketId] = $conn;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function broadcast($payload)
|
|
|
|
|
{
|
|
|
|
|
foreach ($this->connections as $connection) {
|
|
|
|
|
$connection->send(json_encode($payload));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function broadcastToOthers($conn, $payload)
|
|
|
|
|
{
|
2018-11-21 21:36:50 +00:00
|
|
|
Collection::make($this->connections)->reject(function ($connection) use ($conn) {
|
2018-11-21 14:42:04 +00:00
|
|
|
return $connection->socketId === $conn->socketId;
|
|
|
|
|
})->each->send(json_encode($payload));
|
2018-11-21 11:13:40 +00:00
|
|
|
}
|
|
|
|
|
}
|