laravel-websockets/src/Router.php

61 lines
1.4 KiB
PHP
Raw Normal View History

2018-11-20 10:32:56 +00:00
<?php
namespace BeyondCode\LaravelWebSockets;
2018-11-20 10:51:00 +00:00
use Ratchet\WebSocket\WsServer;
2018-11-20 10:32:56 +00:00
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use BeyondCode\LaravelWebSockets\Exceptions\InvalidWebSocketController;
class Router
{
/** @var RouteCollection */
protected $routes;
public function __construct()
{
$this->routes = new RouteCollection;
}
2018-11-20 11:33:40 +00:00
/**
* Add a new WebSocket route.
*
* @param $uri
* @param $action
*/
public function websocket($uri, $action)
2018-11-20 10:32:56 +00:00
{
2018-11-20 10:51:00 +00:00
if (!is_subclass_of($action, WebSocketController::class)) {
2018-11-20 10:32:56 +00:00
throw InvalidWebSocketController::withController($action);
}
2018-11-20 11:33:40 +00:00
$this->addRoute($uri, $action);
}
public function addRoute($uri, $action)
{
2018-11-20 10:32:56 +00:00
$this->routes->add($uri, $this->getRoute($uri, $action));
}
2018-11-20 10:51:00 +00:00
protected function getRoute($uri, $action): Route
2018-11-20 10:32:56 +00:00
{
2018-11-20 10:51:00 +00:00
return new Route($uri, ['_controller' => $this->wrapController($action)], [], [], null, [], ['GET']);
}
/**
* Wrap WebSocket controllers with Ratchets WsServer.
*/
protected function wrapController($controller)
{
if (is_subclass_of($controller, WebSocketController::class)) {
return new WsServer(app($controller));
}
return app($controller);
}
public function getRoutes(): RouteCollection
{
return $this->routes;
2018-11-20 10:32:56 +00:00
}
}