laravel-websockets/src/WebSockets/Messages/PusherChannelProtocolMessag...

65 lines
1.8 KiB
PHP
Raw Normal View History

2018-11-21 22:47:46 +00:00
<?php
2018-11-27 15:30:11 +00:00
namespace BeyondCode\LaravelWebSockets\WebSockets\Messages;
2018-11-21 22:47:46 +00:00
2018-11-27 15:35:28 +00:00
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
2018-11-21 22:47:46 +00:00
use Ratchet\ConnectionInterface;
use stdClass;
2018-12-01 14:09:05 +00:00
class PusherChannelProtocolMessage implements PusherMessage
2018-11-21 22:47:46 +00:00
{
2018-11-27 15:43:25 +00:00
/** @var \stdClass */
2018-11-21 22:47:46 +00:00
protected $payload;
/** @var \React\Socket\ConnectionInterface */
protected $connection;
2018-11-27 15:43:25 +00:00
/** @var \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager */
2018-11-21 22:47:46 +00:00
protected $channelManager;
public function __construct(stdClass $payload, ConnectionInterface $connection, ChannelManager $channelManager)
{
$this->payload = $payload;
$this->connection = $connection;
$this->channelManager = $channelManager;
}
public function respond()
{
$eventName = camel_case(str_after($this->payload->event, ':'));
if (method_exists($this, $eventName)) {
2018-11-25 23:14:50 +00:00
call_user_func([$this, $eventName], $this->connection, $this->payload->data ?? new stdClass());
2018-11-21 22:47:46 +00:00
}
}
2018-11-21 23:15:39 +00:00
/*
2018-11-21 22:47:46 +00:00
* @link https://pusher.com/docs/pusher_protocol#ping-pong
*/
2018-11-21 23:15:39 +00:00
protected function ping(ConnectionInterface $connection)
2018-11-21 22:47:46 +00:00
{
$connection->send(json_encode([
'event' => 'pusher:pong',
]));
}
2018-11-21 23:15:39 +00:00
/*
2018-11-21 22:47:46 +00:00
* @link https://pusher.com/docs/pusher_protocol#pusher-subscribe
*/
2018-11-21 23:15:39 +00:00
protected function subscribe(ConnectionInterface $connection, stdClass $payload)
2018-11-21 22:47:46 +00:00
{
2018-12-01 13:12:15 +00:00
$channel = $this->channelManager->findOrCreate($connection->app->id, $payload->channel);
2018-11-21 22:47:46 +00:00
$channel->subscribe($connection, $payload);
}
public function unsubscribe(ConnectionInterface $connection, stdClass $payload)
{
2018-12-01 13:12:15 +00:00
$channel = $this->channelManager->findOrCreate($connection->app->id, $payload->channel);
2018-11-21 22:47:46 +00:00
$channel->unsubscribe($connection);
}
}