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

62 lines
1.8 KiB
PHP
Raw Normal View History

2018-11-21 11:13:40 +00:00
<?php
2018-11-27 15:11:12 +00:00
namespace BeyondCode\LaravelWebSockets\WebSockets\Pusher\Channels;
2018-11-21 11:13:40 +00:00
2018-11-22 22:58:50 +00:00
use ReflectionClass;
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 array */
2018-11-21 11:13:40 +00:00
protected $channels = [];
2018-11-21 21:11:44 +00:00
/** @var string */
protected $appId;
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-11-22 22:59:32 +00:00
$this->channels[$appId][$channelId] = (new ReflectionClass($this->detectChannelClass($channelId)))
->newInstance($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-11-26 23:07:35 +00:00
protected function detectChannelClass(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;
}
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-24 21:07:53 +00:00
collect($this->channels[$connection->client->appId])->each->unsubscribe($connection);
2018-11-21 21:36:50 +00:00
2018-11-24 21:07:53 +00:00
collect($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-24 21:07:53 +00:00
if (count($this->channels[$connection->client->appId]) === 0) {
unset($this->channels[$connection->client->appId]);
2018-11-21 21:36:50 +00:00
};
}
2018-11-21 11:13:40 +00:00
}