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:07:29 +00:00
|
|
|
use BeyondCode\LaravelWebSockets\WebSocket\Pusher\Channels\ChannelManager;
|
2018-11-21 22:47:46 +00:00
|
|
|
use Ratchet\ConnectionInterface;
|
|
|
|
|
use stdClass;
|
|
|
|
|
|
|
|
|
|
class PusherMessage implements RespondableMessage
|
|
|
|
|
{
|
2018-11-27 15:07:29 +00:00
|
|
|
/** @var \BeyondCode\LaravelWebSockets\WebSocket\Pusher\stdClass */
|
2018-11-21 22:47:46 +00:00
|
|
|
protected $payload;
|
|
|
|
|
|
|
|
|
|
/** @var \React\Socket\ConnectionInterface */
|
|
|
|
|
protected $connection;
|
|
|
|
|
|
2018-11-27 15:07:29 +00:00
|
|
|
/** @var \BeyondCode\LaravelWebSockets\WebSocket\Pusher\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-11-24 21:07:53 +00:00
|
|
|
$channel = $this->channelManager->findOrCreate($connection->client->appId, $payload->channel);
|
2018-11-21 22:47:46 +00:00
|
|
|
|
|
|
|
|
$channel->subscribe($connection, $payload);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function unsubscribe(ConnectionInterface $connection, stdClass $payload)
|
|
|
|
|
{
|
2018-11-24 21:07:53 +00:00
|
|
|
$channel = $this->channelManager->findOrCreate($connection->client->appId, $payload->channel);
|
2018-11-21 22:47:46 +00:00
|
|
|
|
|
|
|
|
$channel->unsubscribe($connection);
|
|
|
|
|
}
|
|
|
|
|
}
|