laravel-websockets/src/WebSockets/Channels/ChannelManager.php

73 lines
2.0 KiB
PHP
Raw Normal View History

2018-11-21 11:13:40 +00:00
<?php
2018-11-27 15:21:31 +00:00
namespace BeyondCode\LaravelWebSockets\WebSockets\Channels;
2018-11-21 11:13:40 +00:00
2018-11-21 21:36:50 +00:00
use Ratchet\ConnectionInterface;
2018-11-21 11:13:40 +00:00
class ChannelManager
{
2018-11-21 21:11:44 +00:00
/** @var string */
protected $appId;
2018-12-01 10:52:47 +00:00
/** @var array */
protected $channels = [];
2018-11-21 21:11:44 +00:00
public function findOrCreate(string $appId, string $channelId): Channel
2018-11-21 11:13:40 +00:00
{
2018-11-21 21:36:50 +00:00
if (!isset($this->channels[$appId][$channelId])) {
2018-12-01 10:52:02 +00:00
$channelClass = $this->determineChannelClass($channelId);
$this->channels[$appId][$channelId] = new $channelClass($channelId);
2018-11-21 11:13:40 +00:00
}
2018-11-21 21:11:44 +00:00
return $this->channels[$appId][$channelId];
2018-11-21 11:13:40 +00:00
}
2018-11-21 23:12:23 +00:00
public function find(string $appId, string $channelId): ?Channel
2018-11-21 14:42:04 +00:00
{
2018-11-21 21:11:44 +00:00
return $this->channels[$appId][$channelId] ?? null;
2018-11-21 14:42:04 +00:00
}
2018-12-01 10:52:02 +00:00
protected function determineChannelClass(string $channelId): string
2018-11-21 11:13:40 +00:00
{
if (starts_with($channelId, 'private-')) {
return PrivateChannel::class;
2018-11-21 21:11:44 +00:00
}
2018-11-21 21:36:50 +00:00
if (starts_with($channelId, 'presence-')) {
2018-11-21 11:13:40 +00:00
return PresenceChannel::class;
}
2018-11-28 23:22:01 +00:00
2018-11-21 11:13:40 +00:00
return Channel::class;
}
2018-11-21 21:36:50 +00:00
2018-11-22 21:20:23 +00:00
public function getChannels(string $appId): array
{
return $this->channels[$appId] ?? [];
}
2018-11-21 21:36:50 +00:00
public function removeFromAllChannels(ConnectionInterface $connection)
{
2018-11-27 20:39:27 +00:00
if (! isset($connection->client)) {
return;
}
2018-11-27 20:42:17 +00:00
/**
* Remove the connection from all channels.
*/
2018-11-28 08:53:03 +00:00
collect(array_get($this->channels, $connection->client->appId, []))->each->unsubscribe($connection);
2018-11-21 21:36:50 +00:00
2018-11-27 20:42:17 +00:00
/**
* Unset all channels that have no connections so we don't leak memory.
*/
2018-11-28 08:53:03 +00:00
collect(array_get($this->channels, $connection->client->appId, []))
2018-11-21 21:36:50 +00:00
->reject->hasConnections()
->each(function (Channel $channel, string $channelId) use ($connection) {
2018-11-24 21:07:53 +00:00
unset($this->channels[$connection->client->appId][$channelId]);
2018-11-21 21:36:50 +00:00
});
2018-11-28 08:53:03 +00:00
if (count(array_get($this->channels, $connection->client->appId, [])) === 0) {
2018-11-24 21:07:53 +00:00
unset($this->channels[$connection->client->appId]);
2018-11-21 21:36:50 +00:00
};
}
2018-11-21 11:13:40 +00:00
}