Apply fixes from StyleCI (#3)

This commit is contained in:
Marcel Pociot 2018-12-04 22:22:33 +01:00 committed by GitHub
parent b3e5df4835
commit 9ce2cc3ff7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
69 changed files with 294 additions and 334 deletions

View File

@ -64,7 +64,7 @@ return [
* When the clean-command is executed, all recorded statistics older than * When the clean-command is executed, all recorded statistics older than
* the number of days specified here will be deleted. * the number of days specified here will be deleted.
*/ */
'delete_statistics_older_than_days' => 60 'delete_statistics_older_than_days' => 60,
], ],
/* /*
@ -89,6 +89,6 @@ return [
/* /*
* Passphrase for your local_cert file. * Passphrase for your local_cert file.
*/ */
'passphrase' => null 'passphrase' => null,
], ],
]; ];

View File

@ -29,12 +29,12 @@ class App
return app(AppProvider::class)->findById($appId); return app(AppProvider::class)->findById($appId);
} }
public static function findByKey(string $appKey): ?App public static function findByKey(string $appKey): ?self
{ {
return app(AppProvider::class)->findByKey($appKey); return app(AppProvider::class)->findByKey($appKey);
} }
public static function findBySecret(string $appSecret): ?App public static function findBySecret(string $appSecret): ?self
{ {
return app(AppProvider::class)->findBySecret($appSecret); return app(AppProvider::class)->findBySecret($appSecret);
} }

View File

@ -12,4 +12,4 @@ interface AppProvider
public function findByKey(string $appKey): ?App; public function findByKey(string $appKey): ?App;
public function findBySecret(string $appSecret): ?App; public function findBySecret(string $appSecret): ?App;
} }

View File

@ -53,7 +53,7 @@ class ConfigAppProvider implements AppProvider
protected function instanciate(?array $appAttributes): ?App protected function instanciate(?array $appAttributes): ?App
{ {
if (!$appAttributes) { if (! $appAttributes) {
return null; return null;
} }
@ -71,7 +71,6 @@ class ConfigAppProvider implements AppProvider
->enableClientMessages($appAttributes['enable_client_messages']) ->enableClientMessages($appAttributes['enable_client_messages'])
->enableStatistics($appAttributes['enable_statistics']); ->enableStatistics($appAttributes['enable_statistics']);
return $app; return $app;
} }
} }

View File

@ -8,7 +8,6 @@ use Illuminate\Database\Eloquent\Builder;
class CleanStatistics extends Command class CleanStatistics extends Command
{ {
protected $signature = 'websockets:clean protected $signature = 'websockets:clean
{appId? : (optional) The app id that will be cleaned.}'; {appId? : (optional) The app id that will be cleaned.}';
@ -36,4 +35,4 @@ class CleanStatistics extends Command
$this->comment('All done!'); $this->comment('All done!');
} }
} }

View File

@ -2,22 +2,20 @@
namespace BeyondCode\LaravelWebSockets\Console; namespace BeyondCode\LaravelWebSockets\Console;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger; use React\Socket\Connector;
use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;
use BeyondCode\LaravelWebSockets\Server\Logger\ConnectionLogger;
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
use BeyondCode\LaravelWebSockets\Statistics\DnsResolver;
use BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger;
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Clue\React\Buzz\Browser; use Clue\React\Buzz\Browser;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use BeyondCode\LaravelWebSockets\Server\WebSocketServerFactory;
use React\EventLoop\Factory as LoopFactory; use React\EventLoop\Factory as LoopFactory;
use React\Socket\Connector; use BeyondCode\LaravelWebSockets\Statistics\DnsResolver;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
use BeyondCode\LaravelWebSockets\Server\WebSocketServerFactory;
use BeyondCode\LaravelWebSockets\Server\Logger\ConnectionLogger;
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger;
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
class StartWebSocketServer extends Command class StartWebSocketServer extends Command
{ {
@ -49,16 +47,16 @@ class StartWebSocketServer extends Command
protected function configureStatisticsLogger() protected function configureStatisticsLogger()
{ {
$connector = new Connector($this->loop, [ $connector = new Connector($this->loop, [
'dns' => new DnsResolver() 'dns' => new DnsResolver(),
]); ]);
$browser = new Browser($this->loop, $connector); $browser = new Browser($this->loop, $connector);
app()->singleton(StatisticsLoggerInterface::class, function() use ($browser) { app()->singleton(StatisticsLoggerInterface::class, function () use ($browser) {
return new HttpStatisticsLogger(app(ChannelManager::class), $browser); return new HttpStatisticsLogger(app(ChannelManager::class), $browser);
}); });
$this->loop->addPeriodicTimer(config('websockets.statistics.interval_in_seconds'), function() { $this->loop->addPeriodicTimer(config('websockets.statistics.interval_in_seconds'), function () {
StatisticsLogger::save(); StatisticsLogger::save();
}); });
@ -67,7 +65,7 @@ class StartWebSocketServer extends Command
protected function configureHttpLogger() protected function configureHttpLogger()
{ {
app()->singleton(HttpLogger::class, function() { app()->singleton(HttpLogger::class, function () {
return (new HttpLogger($this->output)) return (new HttpLogger($this->output))
->enable(config('app.debug')) ->enable(config('app.debug'))
->verbose($this->output->isVerbose()); ->verbose($this->output->isVerbose());
@ -78,7 +76,7 @@ class StartWebSocketServer extends Command
protected function configureMessageLogger() protected function configureMessageLogger()
{ {
app()->singleton(WebsocketsLogger::class, function() { app()->singleton(WebsocketsLogger::class, function () {
return (new WebsocketsLogger($this->output)) return (new WebsocketsLogger($this->output))
->enable(config('app.debug')) ->enable(config('app.debug'))
->verbose($this->output->isVerbose()); ->verbose($this->output->isVerbose());
@ -89,7 +87,7 @@ class StartWebSocketServer extends Command
protected function configureConnectionLogger() protected function configureConnectionLogger()
{ {
app()->bind(ConnectionLogger::class, function() { app()->bind(ConnectionLogger::class, function () {
return (new ConnectionLogger($this->output)) return (new ConnectionLogger($this->output))
->enable(config('app.debug')) ->enable(config('app.debug'))
->verbose($this->output->isVerbose()); ->verbose($this->output->isVerbose());
@ -111,7 +109,7 @@ class StartWebSocketServer extends Command
$routes = WebSocketsRouter::getRoutes(); $routes = WebSocketsRouter::getRoutes();
/** 🛰 Start the server 🛰 */ /* 🛰 Start the server 🛰 */
(new WebSocketServerFactory()) (new WebSocketServerFactory())
->setLoop($this->loop) ->setLoop($this->loop)
->useRoutes($routes) ->useRoutes($routes)

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\Dashboard; namespace BeyondCode\LaravelWebSockets\Dashboard;
use stdClass;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager; use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use stdClass;
class DashboardLogger class DashboardLogger
{ {
@ -76,7 +76,7 @@ class DashboardLogger
public static function log($appId, string $type, array $attributes = []) public static function log($appId, string $type, array $attributes = [])
{ {
$channelName = static::LOG_CHANNEL_PREFIX . $type; $channelName = static::LOG_CHANNEL_PREFIX.$type;
$channel = app(ChannelManager::class)->find($appId, $channelName); $channel = app(ChannelManager::class)->find($appId, $channelName);
@ -85,9 +85,8 @@ class DashboardLogger
'channel' => $channelName, 'channel' => $channelName,
'data' => [ 'data' => [
'type' => $type, 'type' => $type,
'time' => strftime("%H:%M:%S") 'time' => strftime('%H:%M:%S'),
] + $attributes, ] + $attributes,
]); ]);
} }
}
}

View File

@ -16,4 +16,4 @@ class AuthenticateDashboard
*/ */
return $broadcaster->validAuthenticationResponse($request, []); return $broadcaster->validAuthenticationResponse($request, []);
} }
} }

View File

@ -11,7 +11,7 @@ class DashboardApiController
$statisticData = $statistics->map(function ($statistic) { $statisticData = $statistics->map(function ($statistic) {
return [ return [
'timestamp' => (string)$statistic->created_at, 'timestamp' => (string) $statistic->created_at,
'peak_connection_count' => $statistic->peak_connection_count, 'peak_connection_count' => $statistic->peak_connection_count,
'websocket_message_count' => $statistic->websocket_message_count, 'websocket_message_count' => $statistic->websocket_message_count,
'api_message_count' => $statistic->api_message_count, 'api_message_count' => $statistic->api_message_count,
@ -30,7 +30,7 @@ class DashboardApiController
'api_message_count' => [ 'api_message_count' => [
'x' => $statisticData->pluck('timestamp'), 'x' => $statisticData->pluck('timestamp'),
'y' => $statisticData->pluck('api_message_count'), 'y' => $statisticData->pluck('api_message_count'),
] ],
]; ];
} }
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers; namespace BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers;
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
use Pusher\Pusher; use Pusher\Pusher;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster; use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster;
class SendMessage class SendMessage

View File

@ -13,4 +13,4 @@ class ShowDashboard
'apps' => $apps->all(), 'apps' => $apps->all(),
]); ]);
} }
} }

View File

@ -10,4 +10,4 @@ class Authorize
{ {
return Gate::check('viewWebSocketsDashboard') ? $next($request) : abort(403); return Gate::check('viewWebSocketsDashboard') ? $next($request) : abort(403);
} }
} }

View File

@ -15,4 +15,4 @@ class InvalidApp extends Exception
{ {
return new static("{$name} is required but was empty for app id `{$appId}`."); return new static("{$name} is required but was empty for app id `{$appId}`.");
} }
} }

View File

@ -12,4 +12,4 @@ class InvalidWebSocketController extends \Exception
return new static("Invalid WebSocket Controller provided. Expected instance of `{$messageComponentInterfaceClass}`, but received `{$controllerClass}`."); return new static("Invalid WebSocket Controller provided. Expected instance of `{$messageComponentInterfaceClass}`, but received `{$controllerClass}`.");
} }
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\Facades; namespace BeyondCode\LaravelWebSockets\Facades;
use Illuminate\Support\Facades\Facade;
use BeyondCode\LaravelWebSockets\Statistics\Logger\FakeStatisticsLogger; use BeyondCode\LaravelWebSockets\Statistics\Logger\FakeStatisticsLogger;
use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface; use BeyondCode\LaravelWebSockets\Statistics\Logger\StatisticsLogger as StatisticsLoggerInterface;
use Illuminate\Support\Facades\Facade;
/** @see \BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger */ /** @see \BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger */
class StatisticsLogger extends Facade class StatisticsLogger extends Facade

View File

@ -2,10 +2,6 @@
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers; namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
use BeyondCode\LaravelWebSockets\Apps\App;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Events\ExceptionThrown;
use BeyondCode\LaravelWebSockets\QueryParameters;
use Exception; use Exception;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
@ -14,6 +10,8 @@ use Illuminate\Http\JsonResponse;
use GuzzleHttp\Psr7\ServerRequest; use GuzzleHttp\Psr7\ServerRequest;
use Ratchet\Http\HttpServerInterface; use Ratchet\Http\HttpServerInterface;
use Psr\Http\Message\RequestInterface; use Psr\Http\Message\RequestInterface;
use BeyondCode\LaravelWebSockets\Apps\App;
use BeyondCode\LaravelWebSockets\QueryParameters;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager; use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
@ -50,24 +48,24 @@ abstract class Controller implements HttpServerInterface
$connection->close(); $connection->close();
} }
function onMessage(ConnectionInterface $from, $msg) public function onMessage(ConnectionInterface $from, $msg)
{ {
} }
function onClose(ConnectionInterface $connection) public function onClose(ConnectionInterface $connection)
{ {
} }
function onError(ConnectionInterface $connection, Exception $exception) public function onError(ConnectionInterface $connection, Exception $exception)
{ {
if (! $exception instanceof HttpException) { if (! $exception instanceof HttpException) {
return; return;
} }
$response = new Response($exception->getStatusCode(), [ $response = new Response($exception->getStatusCode(), [
'Content-Type' => 'application/json' 'Content-Type' => 'application/json',
], json_encode([ ], json_encode([
'error' => $exception->getMessage() 'error' => $exception->getMessage(),
])); ]));
$connection->send(\GuzzleHttp\Psr7\str($response)); $connection->send(\GuzzleHttp\Psr7\str($response));
@ -86,11 +84,10 @@ abstract class Controller implements HttpServerInterface
protected function ensureValidSignature(Request $request) protected function ensureValidSignature(Request $request)
{ {
$signature = $signature =
"{$request->getMethod()}\n/{$request->path()}\n" . "{$request->getMethod()}\n/{$request->path()}\n".
"auth_key={$request->get('auth_key')}" . "auth_key={$request->get('auth_key')}".
"&auth_timestamp={$request->get('auth_timestamp')}" . "&auth_timestamp={$request->get('auth_timestamp')}".
"&auth_version={$request->get('auth_version')}"; "&auth_version={$request->get('auth_version')}";
if ($request->getContent() !== '') { if ($request->getContent() !== '') {
@ -109,4 +106,4 @@ abstract class Controller implements HttpServerInterface
} }
abstract public function __invoke(Request $request); abstract public function __invoke(Request $request);
} }

View File

@ -2,7 +2,6 @@
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers; namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\Controller;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
@ -18,4 +17,4 @@ class FetchChannelController extends Controller
return $channel->toArray(); return $channel->toArray();
} }
} }

View File

@ -2,7 +2,6 @@
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers; namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\Controller;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel; use BeyondCode\LaravelWebSockets\WebSockets\Channels\PresenceChannel;
@ -26,7 +25,7 @@ class FetchChannelsController extends Controller
return [ return [
'user_count' => count($channel->getUsers()), 'user_count' => count($channel->getUsers()),
]; ];
})->toArray() })->toArray(),
]; ];
} }
} }

View File

@ -2,7 +2,6 @@
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers; namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\Controller;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
@ -25,7 +24,7 @@ class FetchUsersController extends Controller
return [ return [
'users' => Collection::make($channel->getUsers())->map(function ($user) { 'users' => Collection::make($channel->getUsers())->map(function ($user) {
return ['id' => $user->user_id]; return ['id' => $user->user_id];
})->values() })->values(),
]; ];
} }
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers; namespace BeyondCode\LaravelWebSockets\HttpApi\Controllers;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
class TriggerEventController extends Controller class TriggerEventController extends Controller
{ {
@ -33,4 +33,4 @@ class TriggerEventController extends Controller
return $request->json()->all(); return $request->json()->all();
} }
} }

View File

@ -32,4 +32,4 @@ class QueryParameters
{ {
return $this->all()[$name] ?? ''; return $this->all()[$name] ?? '';
} }
} }

View File

@ -12,4 +12,4 @@ class HttpServer extends \Ratchet\Http\HttpServer
$this->_reqParser->maxSize = $maxRequestSize; $this->_reqParser->maxSize = $maxRequestSize;
} }
} }

View File

@ -9,9 +9,9 @@ class ConnectionLogger extends Logger implements ConnectionInterface
/** @var \Ratchet\ConnectionInterface */ /** @var \Ratchet\ConnectionInterface */
protected $connection; protected $connection;
public static function decorate(ConnectionInterface $app): ConnectionLogger public static function decorate(ConnectionInterface $app): self
{ {
$logger = app(ConnectionLogger::class); $logger = app(self::class);
return $logger->setConnection($app); return $logger->setConnection($app);
} }
@ -54,11 +54,13 @@ class ConnectionLogger extends Logger implements ConnectionInterface
return $this->connection->$name; return $this->connection->$name;
} }
public function __isset($name) { public function __isset($name)
{
return isset($this->connection->$name); return isset($this->connection->$name);
} }
public function __unset($name) { public function __unset($name)
{
unset($this->connection->$name); unset($this->connection->$name);
} }
} }

View File

@ -11,9 +11,9 @@ class HttpLogger extends Logger implements MessageComponentInterface
/** @var \Ratchet\Http\HttpServerInterface */ /** @var \Ratchet\Http\HttpServerInterface */
protected $app; protected $app;
public static function decorate(MessageComponentInterface $app): HttpLogger public static function decorate(MessageComponentInterface $app): self
{ {
$logger = app(HttpLogger::class); $logger = app(self::class);
return $logger->setApp($app); return $logger->setApp($app);
} }
@ -54,5 +54,4 @@ class HttpLogger extends Logger implements MessageComponentInterface
$this->app->onError($connection, $exception); $this->app->onError($connection, $exception);
} }
}
}

View File

@ -67,4 +67,4 @@ class Logger
$this->consoleOutput->writeln($styled); $this->consoleOutput->writeln($styled);
} }
} }

View File

@ -2,20 +2,20 @@
namespace BeyondCode\LaravelWebSockets\Server\Logger; namespace BeyondCode\LaravelWebSockets\Server\Logger;
use BeyondCode\LaravelWebSockets\QueryParameters;
use Exception; use Exception;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface; use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface; use Ratchet\WebSocket\MessageComponentInterface;
use BeyondCode\LaravelWebSockets\QueryParameters;
class WebsocketsLogger extends Logger implements MessageComponentInterface class WebsocketsLogger extends Logger implements MessageComponentInterface
{ {
/** @var \Ratchet\Http\HttpServerInterface */ /** @var \Ratchet\Http\HttpServerInterface */
protected $app; protected $app;
public static function decorate(MessageComponentInterface $app): WebsocketsLogger public static function decorate(MessageComponentInterface $app): self
{ {
$logger = app(WebsocketsLogger::class); $logger = app(self::class);
return $logger->setApp($app); return $logger->setApp($app);
} }
@ -68,5 +68,4 @@ class WebsocketsLogger extends Logger implements MessageComponentInterface
$this->app->onError(ConnectionLogger::decorate($connection), $exception); $this->app->onError(ConnectionLogger::decorate($connection), $exception);
} }
}
}

View File

@ -5,8 +5,8 @@ namespace BeyondCode\LaravelWebSockets\Server;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use Ratchet\Http\CloseResponseTrait; use Ratchet\Http\CloseResponseTrait;
use Ratchet\Http\HttpServerInterface; use Ratchet\Http\HttpServerInterface;
use Ratchet\MessageComponentInterface;
use Psr\Http\Message\RequestInterface; use Psr\Http\Message\RequestInterface;
use Ratchet\MessageComponentInterface;
class OriginCheck implements HttpServerInterface class OriginCheck implements HttpServerInterface
{ {
@ -33,28 +33,28 @@ class OriginCheck implements HttpServerInterface
return $this->_component->onOpen($connection, $request); return $this->_component->onOpen($connection, $request);
} }
function onMessage(ConnectionInterface $from, $msg) public function onMessage(ConnectionInterface $from, $msg)
{ {
return $this->_component->onMessage($from, $msg); return $this->_component->onMessage($from, $msg);
} }
function onClose(ConnectionInterface $connection) public function onClose(ConnectionInterface $connection)
{ {
return $this->_component->onClose($connection); return $this->_component->onClose($connection);
} }
function onError(ConnectionInterface $connection, \Exception $e) public function onError(ConnectionInterface $connection, \Exception $e)
{ {
return $this->_component->onError($connection, $e); return $this->_component->onError($connection, $e);
} }
protected function verifyOrigin(ConnectionInterface $connection, RequestInterface $request) protected function verifyOrigin(ConnectionInterface $connection, RequestInterface $request)
{ {
$header = (string)$request->getHeader('Origin')[0]; $header = (string) $request->getHeader('Origin')[0];
$origin = parse_url($header, PHP_URL_HOST) ?: $header; $origin = parse_url($header, PHP_URL_HOST) ?: $header;
if (!empty($this->allowedOrigins) && !in_array($origin, $this->allowedOrigins)) { if (! empty($this->allowedOrigins) && ! in_array($origin, $this->allowedOrigins)) {
return $this->close($connection, 403); return $this->close($connection, 403);
} }
} }
} }

View File

@ -2,17 +2,17 @@
namespace BeyondCode\LaravelWebSockets\Server; namespace BeyondCode\LaravelWebSockets\Server;
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelsController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchUsersController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\TriggerEventController;
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler;
use Ratchet\WebSocket\MessageComponentInterface;
use Ratchet\WebSocket\WsServer; use Ratchet\WebSocket\WsServer;
use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RouteCollection;
use Ratchet\WebSocket\MessageComponentInterface;
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler;
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;
use BeyondCode\LaravelWebSockets\Exceptions\InvalidWebSocketController; use BeyondCode\LaravelWebSockets\Exceptions\InvalidWebSocketController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchUsersController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\TriggerEventController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelsController;
class Router class Router
{ {
@ -66,7 +66,7 @@ class Router
public function webSocket(string $uri, $action) public function webSocket(string $uri, $action)
{ {
if (!is_subclass_of($action, MessageComponentInterface::class)) { if (! is_subclass_of($action, MessageComponentInterface::class)) {
throw InvalidWebSocketController::withController($action); throw InvalidWebSocketController::withController($action);
} }
@ -103,4 +103,4 @@ class Router
return new WsServer($app); return new WsServer($app);
} }
} }

View File

@ -2,17 +2,17 @@
namespace BeyondCode\LaravelWebSockets\Server; namespace BeyondCode\LaravelWebSockets\Server;
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
use Ratchet\Http\Router; use Ratchet\Http\Router;
use React\Socket\SecureServer;
use React\Socket\Server; use React\Socket\Server;
use Ratchet\Server\IoServer; use Ratchet\Server\IoServer;
use React\Socket\SecureServer;
use React\EventLoop\LoopInterface; use React\EventLoop\LoopInterface;
use React\EventLoop\Factory as LoopFactory; use React\EventLoop\Factory as LoopFactory;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Console\Output\OutputInterface;
use BeyondCode\LaravelWebSockets\Server\Logger\HttpLogger;
class WebSocketServerFactory class WebSocketServerFactory
{ {

View File

@ -19,4 +19,4 @@ class DnsResolver extends Resolver
{ {
return new FulfilledPromise('127.0.0.1'); return new FulfilledPromise('127.0.0.1');
} }
} }

View File

@ -2,11 +2,11 @@
namespace BeyondCode\LaravelWebsockets\Statistics\Events; namespace BeyondCode\LaravelWebsockets\Statistics\Events;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger; use Illuminate\Queue\SerializesModels;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels; use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
class StatisticsUpdated implements ShouldBroadcast class StatisticsUpdated implements ShouldBroadcast
{ {
@ -23,7 +23,7 @@ class StatisticsUpdated implements ShouldBroadcast
public function broadcastWith() public function broadcastWith()
{ {
return [ return [
'time' => (string)$this->webSocketsStatisticsEntry->created_at, 'time' => (string) $this->webSocketsStatisticsEntry->created_at,
'app_id' => $this->webSocketsStatisticsEntry->app_id, 'app_id' => $this->webSocketsStatisticsEntry->app_id,
'peak_connection_count' => $this->webSocketsStatisticsEntry->peak_connection_count, 'peak_connection_count' => $this->webSocketsStatisticsEntry->peak_connection_count,
'websocket_message_count' => $this->webSocketsStatisticsEntry->websocket_message_count, 'websocket_message_count' => $this->webSocketsStatisticsEntry->websocket_message_count,
@ -33,7 +33,7 @@ class StatisticsUpdated implements ShouldBroadcast
public function broadcastOn() public function broadcastOn()
{ {
$channelName = str_after(DashboardLogger::LOG_CHANNEL_PREFIX . 'statistics', 'private-'); $channelName = str_after(DashboardLogger::LOG_CHANNEL_PREFIX.'statistics', 'private-');
return new PrivateChannel($channelName); return new PrivateChannel($channelName);
} }
@ -42,4 +42,4 @@ class StatisticsUpdated implements ShouldBroadcast
{ {
return 'statistics-updated'; return 'statistics-updated';
} }
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\Statistics\Http\Controllers; namespace BeyondCode\LaravelWebSockets\Statistics\Http\Controllers;
use BeyondCode\LaravelWebSockets\Statistics\Events\StatisticsUpdated;
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
use BeyondCode\LaravelWebSockets\Statistics\Events\StatisticsUpdated;
class WebSocketStatisticsEntriesController class WebSocketStatisticsEntriesController
{ {
@ -25,4 +25,4 @@ class WebSocketStatisticsEntriesController
return 'ok'; return 'ok';
} }
} }

View File

@ -10,4 +10,4 @@ class Authorize
{ {
return is_null(App::findBySecret($request->secret)) ? abort(403) : $next($request); return is_null(App::findBySecret($request->secret)) ? abort(403) : $next($request);
} }
} }

View File

@ -2,41 +2,31 @@
namespace BeyondCode\LaravelWebSockets\Statistics\Logger; namespace BeyondCode\LaravelWebSockets\Statistics\Logger;
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use GuzzleHttp\Client;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
class FakeStatisticsLogger implements StatisticsLogger class FakeStatisticsLogger implements StatisticsLogger
{ {
public function webSocketMessage(ConnectionInterface $connection) public function webSocketMessage(ConnectionInterface $connection)
{ {
} }
public function apiMessage($appId) public function apiMessage($appId)
{ {
} }
public function connection(ConnectionInterface $connection) public function connection(ConnectionInterface $connection)
{ {
} }
public function disconnection(ConnectionInterface $connection) public function disconnection(ConnectionInterface $connection)
{ {
} }
protected function initializeStatistics($id) protected function initializeStatistics($id)
{ {
} }
public function save() public function save()
{ {
} }
} }

View File

@ -2,13 +2,13 @@
namespace BeyondCode\LaravelWebSockets\Statistics\Logger; namespace BeyondCode\LaravelWebSockets\Statistics\Logger;
use Clue\React\Buzz\Browser;
use Ratchet\ConnectionInterface;
use function GuzzleHttp\Psr7\stream_for;
use BeyondCode\LaravelWebSockets\Apps\App; use BeyondCode\LaravelWebSockets\Apps\App;
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
use BeyondCode\LaravelWebSockets\Statistics\Statistic; use BeyondCode\LaravelWebSockets\Statistics\Statistic;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager; use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Clue\React\Buzz\Browser; use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
use function GuzzleHttp\Psr7\stream_for;
use Ratchet\ConnectionInterface;
class HttpStatisticsLogger implements StatisticsLogger class HttpStatisticsLogger implements StatisticsLogger
{ {
@ -58,7 +58,7 @@ class HttpStatisticsLogger implements StatisticsLogger
protected function findOrMakeStatisticForAppId($appId): Statistic protected function findOrMakeStatisticForAppId($appId): Statistic
{ {
if (!isset($this->statistics[$appId])) { if (! isset($this->statistics[$appId])) {
$this->statistics[$appId] = new Statistic($appId); $this->statistics[$appId] = new Statistic($appId);
} }
@ -68,13 +68,12 @@ class HttpStatisticsLogger implements StatisticsLogger
public function save() public function save()
{ {
foreach ($this->statistics as $appId => $statistic) { foreach ($this->statistics as $appId => $statistic) {
if (! $statistic->isEnabled()) {
if (!$statistic->isEnabled()) {
continue; continue;
} }
$postData = array_merge($statistic->toArray(), [ $postData = array_merge($statistic->toArray(), [
'secret' => App::findById($appId)->secret 'secret' => App::findById($appId)->secret,
]); ]);
$this $this
@ -89,4 +88,4 @@ class HttpStatisticsLogger implements StatisticsLogger
$statistic->reset($currentConnectionCount); $statistic->reset($currentConnectionCount);
} }
} }
} }

View File

@ -15,4 +15,4 @@ interface StatisticsLogger
public function disconnection(connectionInterface $connection); public function disconnection(connectionInterface $connection);
public function save(); public function save();
} }

View File

@ -9,4 +9,4 @@ class WebSocketsStatisticsEntry extends Model
protected $guarded = []; protected $guarded = [];
protected $table = 'websockets_statistics_entries'; protected $table = 'websockets_statistics_entries';
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebSockets\Statistics\Rules; namespace BeyondCode\LaravelWebSockets\Statistics\Rules;
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
use Illuminate\Contracts\Validation\Rule; use Illuminate\Contracts\Validation\Rule;
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
class AppId implements Rule class AppId implements Rule
{ {
@ -17,4 +17,5 @@ class AppId implements Rule
public function message() public function message()
{ {
return 'There is no app registered with the given id. Make sure the websockets config file contains an app for this id or that your custom AppProvider returns an app for this id.'; return 'There is no app registered with the given id. Make sure the websockets config file contains an app for this id or that your custom AppProvider returns an app for this id.';
}} }
}

View File

@ -72,4 +72,4 @@ class Statistic
'api_message_count' => $this->apiMessageCount, 'api_message_count' => $this->apiMessageCount,
]; ];
} }
} }

View File

@ -2,11 +2,10 @@
namespace BeyondCode\LaravelWebSockets\WebSockets\Channels; namespace BeyondCode\LaravelWebSockets\WebSockets\Channels;
use stdClass;
use Ratchet\ConnectionInterface;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger; use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature; use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature;
use Illuminate\Support\Collection;
use Ratchet\ConnectionInterface;
use stdClass;
class Channel class Channel
{ {
@ -53,7 +52,7 @@ class Channel
$connection->send(json_encode([ $connection->send(json_encode([
'event' => 'pusher_internal:subscription_succeeded', 'event' => 'pusher_internal:subscription_succeeded',
'channel' => $this->channelName 'channel' => $this->channelName,
])); ]));
} }
@ -108,7 +107,7 @@ class Channel
{ {
return [ return [
'occupied' => count($this->subscribedConnections) > 0, 'occupied' => count($this->subscribedConnections) > 0,
'subscription_count' => count($this->subscribedConnections) 'subscription_count' => count($this->subscribedConnections),
]; ];
} }
} }

View File

@ -14,7 +14,7 @@ class ChannelManager
public function findOrCreate(string $appId, string $channelName): Channel public function findOrCreate(string $appId, string $channelName): Channel
{ {
if (!isset($this->channels[$appId][$channelName])) { if (! isset($this->channels[$appId][$channelName])) {
$channelClass = $this->determineChannelClass($channelName); $channelClass = $this->determineChannelClass($channelName);
$this->channels[$appId][$channelName] = new $channelClass($channelName); $this->channels[$appId][$channelName] = new $channelClass($channelName);
@ -56,16 +56,16 @@ class ChannelManager
public function removeFromAllChannels(ConnectionInterface $connection) public function removeFromAllChannels(ConnectionInterface $connection)
{ {
if (!isset($connection->app)) { if (! isset($connection->app)) {
return; return;
} }
/** /*
* Remove the connection from all channels. * Remove the connection from all channels.
*/ */
collect(array_get($this->channels, $connection->app->id, []))->each->unsubscribe($connection); collect(array_get($this->channels, $connection->app->id, []))->each->unsubscribe($connection);
/** /*
* Unset all channels that have no connections so we don't leak memory. * Unset all channels that have no connections so we don't leak memory.
*/ */
collect(array_get($this->channels, $connection->app->id, [])) collect(array_get($this->channels, $connection->app->id, []))
@ -76,6 +76,6 @@ class ChannelManager
if (count(array_get($this->channels, $connection->app->id, [])) === 0) { if (count(array_get($this->channels, $connection->app->id, [])) === 0) {
unset($this->channels[$connection->app->id]); unset($this->channels[$connection->app->id]);
}; }
} }
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebSockets\WebSockets\Channels; namespace BeyondCode\LaravelWebSockets\WebSockets\Channels;
use Ratchet\ConnectionInterface;
use stdClass; use stdClass;
use Ratchet\ConnectionInterface;
class PresenceChannel extends Channel class PresenceChannel extends Channel
{ {
@ -30,13 +30,13 @@ class PresenceChannel extends Channel
$connection->send(json_encode([ $connection->send(json_encode([
'event' => 'pusher_internal:subscription_succeeded', 'event' => 'pusher_internal:subscription_succeeded',
'channel' => $this->channelName, 'channel' => $this->channelName,
'data' => json_encode($this->getChannelData()) 'data' => json_encode($this->getChannelData()),
])); ]));
$this->broadcastToOthers($connection, [ $this->broadcastToOthers($connection, [
'event' => 'pusher_internal:member_added', 'event' => 'pusher_internal:member_added',
'channel' => $this->channelName, 'channel' => $this->channelName,
'data' => json_encode($channelData) 'data' => json_encode($channelData),
]); ]);
} }
@ -52,8 +52,8 @@ class PresenceChannel extends Channel
'event' => 'pusher_internal:member_removed', 'event' => 'pusher_internal:member_removed',
'channel' => $this->channelName, 'channel' => $this->channelName,
'data' => json_encode([ 'data' => json_encode([
'user_id' => $this->users[$connection->socketId]->user_id 'user_id' => $this->users[$connection->socketId]->user_id,
]) ]),
]); ]);
unset($this->users[$connection->socketId]); unset($this->users[$connection->socketId]);
@ -80,7 +80,7 @@ class PresenceChannel extends Channel
protected function getUserIds(): array protected function getUserIds(): array
{ {
$userIds = array_map(function ($channelData) { $userIds = array_map(function ($channelData) {
return (string)$channelData->user_id; return (string) $channelData->user_id;
}, $this->users); }, $this->users);
return array_values($userIds); return array_values($userIds);
@ -96,4 +96,4 @@ class PresenceChannel extends Channel
return $hash; return $hash;
} }
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebSockets\WebSockets\Channels; namespace BeyondCode\LaravelWebSockets\WebSockets\Channels;
use Ratchet\ConnectionInterface;
use stdClass; use stdClass;
use Ratchet\ConnectionInterface;
class PrivateChannel extends Channel class PrivateChannel extends Channel
{ {
@ -13,4 +13,4 @@ class PrivateChannel extends Channel
parent::subscribe($connection, $payload); parent::subscribe($connection, $payload);
} }
} }

View File

@ -10,4 +10,4 @@ class InvalidConnection extends WebSocketException
$this->code = 4009; $this->code = 4009;
} }
} }

View File

@ -10,4 +10,4 @@ class InvalidSignature extends WebSocketException
$this->code = 4009; $this->code = 4009;
} }
} }

View File

@ -10,4 +10,4 @@ class UnknownAppKey extends WebSocketException
$this->code = 4001; $this->code = 4001;
} }
} }

View File

@ -12,8 +12,8 @@ class WebSocketException extends Exception
'event' => 'pusher:error', 'event' => 'pusher:error',
'data' => [ 'data' => [
'message' => $this->getMessage(), 'message' => $this->getMessage(),
'code' => $this->getCode() 'code' => $this->getCode(),
] ],
]; ];
} }
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\WebSockets\Messages; namespace BeyondCode\LaravelWebSockets\WebSockets\Messages;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Ratchet\ConnectionInterface;
use stdClass; use stdClass;
use Ratchet\ConnectionInterface;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
class PusherChannelProtocolMessage implements PusherMessage class PusherChannelProtocolMessage implements PusherMessage
{ {

View File

@ -2,11 +2,10 @@
namespace BeyondCode\LaravelWebSockets\WebSockets\Messages; namespace BeyondCode\LaravelWebSockets\WebSockets\Messages;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Events\ClientMessageSent;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Ratchet\ConnectionInterface;
use stdClass; use stdClass;
use Ratchet\ConnectionInterface;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
class PusherClientMessage implements PusherMessage class PusherClientMessage implements PusherMessage
{ {
@ -30,7 +29,7 @@ class PusherClientMessage implements PusherMessage
public function respond() public function respond()
{ {
if (!starts_with($this->payload->event, 'client-')) { if (! starts_with($this->payload->event, 'client-')) {
return; return;
} }
@ -44,4 +43,4 @@ class PusherClientMessage implements PusherMessage
optional($channel)->broadcastToOthers($this->connection, $this->payload); optional($channel)->broadcastToOthers($this->connection, $this->payload);
} }
} }

View File

@ -1,7 +1,8 @@
<?php <?php
namespace BeyondCode\LaravelWebSockets\WebSockets\Messages; namespace BeyondCode\LaravelWebSockets\WebSockets\Messages;
interface PusherMessage interface PusherMessage
{ {
public function respond(); public function respond();
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\WebSockets\Messages; namespace BeyondCode\LaravelWebSockets\WebSockets\Messages;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface; use Ratchet\RFC6455\Messaging\MessageInterface;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
class PusherMessageFactory class PusherMessageFactory
{ {
@ -19,4 +19,4 @@ class PusherMessageFactory
? new PusherChannelProtocolMessage($payload, $connection, $channelManager) ? new PusherChannelProtocolMessage($payload, $connection, $channelManager)
: new PusherClientMessage($payload, $connection, $channelManager); : new PusherClientMessage($payload, $connection, $channelManager);
} }
} }

View File

@ -2,18 +2,18 @@
namespace BeyondCode\LaravelWebSockets\WebSockets; namespace BeyondCode\LaravelWebSockets\WebSockets;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\WebSocketException;
use BeyondCode\LaravelWebSockets\WebSockets\Messages\PusherMessageFactory;
use BeyondCode\LaravelWebSockets\QueryParameters;
use Exception; use Exception;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use BeyondCode\LaravelWebSockets\Apps\App; use BeyondCode\LaravelWebSockets\Apps\App;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;
use BeyondCode\LaravelWebSockets\QueryParameters;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use BeyondCode\LaravelWebSockets\Dashboard\DashboardLogger;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager; use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey; use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey;
use Ratchet\WebSocket\MessageComponentInterface; use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\WebSocketException;
use BeyondCode\LaravelWebSockets\WebSockets\Messages\PusherMessageFactory;
class WebSocketHandler implements MessageComponentInterface class WebSocketHandler implements MessageComponentInterface
{ {
@ -64,7 +64,7 @@ class WebSocketHandler implements MessageComponentInterface
{ {
$appKey = QueryParameters::create($connection->httpRequest)->get('appKey'); $appKey = QueryParameters::create($connection->httpRequest)->get('appKey');
if (!$app = App::findByKey($appKey)) { if (! $app = App::findByKey($appKey)) {
throw new UnknownAppKey($appKey); throw new UnknownAppKey($appKey);
} }
@ -75,7 +75,7 @@ class WebSocketHandler implements MessageComponentInterface
protected function generateSocketId(ConnectionInterface $connection) protected function generateSocketId(ConnectionInterface $connection)
{ {
$socketId = sprintf("%d.%d", random_int(1, 1000000000), random_int(1, 1000000000)); $socketId = sprintf('%d.%d', random_int(1, 1000000000), random_int(1, 1000000000));
$connection->socketId = $socketId; $connection->socketId = $socketId;
@ -89,7 +89,7 @@ class WebSocketHandler implements MessageComponentInterface
'data' => json_encode([ 'data' => json_encode([
'socket_id' => $connection->socketId, 'socket_id' => $connection->socketId,
'activity_timeout' => 30, 'activity_timeout' => 30,
]) ]),
])); ]));
DashboardLogger::connection($connection); DashboardLogger::connection($connection);
@ -98,4 +98,4 @@ class WebSocketHandler implements MessageComponentInterface
return $this; return $this;
} }
} }

View File

@ -2,33 +2,31 @@
namespace BeyondCode\LaravelWebSockets; namespace BeyondCode\LaravelWebSockets;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\AuthenticateDashboard;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\DashboardApiController;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\SendMessage;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\ShowDashboard;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize as AuthorizeDashboard;
use BeyondCode\LaravelWebSockets\Statistics\Http\Middleware\Authorize as AuthorizeStatistics;
use BeyondCode\LaravelWebSockets\Server\Router;
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
use BeyondCode\LaravelWebSockets\Statistics\Logger\HttpStatisticsLogger;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use BeyondCode\LaravelWebSockets\Server\Router;
use BeyondCode\LaravelWebSockets\Apps\AppProvider;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager; use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use Illuminate\Support\Str; use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\SendMessage;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\ShowDashboard;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\AuthenticateDashboard;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Controllers\DashboardApiController;
use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize as AuthorizeDashboard;
use BeyondCode\LaravelWebSockets\Statistics\Http\Middleware\Authorize as AuthorizeStatistics;
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
class WebSocketsServiceProvider extends ServiceProvider class WebSocketsServiceProvider extends ServiceProvider
{ {
public function boot() public function boot()
{ {
$this->publishes([ $this->publishes([
__DIR__ . '/../config/websockets.php' => base_path('config/websockets.php'), __DIR__.'/../config/websockets.php' => base_path('config/websockets.php'),
], 'config'); ], 'config');
if (!class_exists('CreateWebSocketsStatisticsEntries')) { if (! class_exists('CreateWebSocketsStatisticsEntries')) {
$this->publishes([ $this->publishes([
__DIR__ . '/../database/migrations/create_websockets_statistics_entries_table.php.stub' => database_path('migrations/' . date('Y_m_d_His', time()) . '_create_websockets_statistics_entries_table.php'), __DIR__.'/../database/migrations/create_websockets_statistics_entries_table.php.stub' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_websockets_statistics_entries_table.php'),
], 'migrations'); ], 'migrations');
} }
@ -36,7 +34,7 @@ class WebSocketsServiceProvider extends ServiceProvider
->registerRoutes() ->registerRoutes()
->registerDashboardGate(); ->registerDashboardGate();
$this->loadViewsFrom(__DIR__ . '/../resources/views/', 'websockets'); $this->loadViewsFrom(__DIR__.'/../resources/views/', 'websockets');
$this->commands([ $this->commands([
Console\StartWebSocketServer::class, Console\StartWebSocketServer::class,
@ -46,7 +44,7 @@ class WebSocketsServiceProvider extends ServiceProvider
public function register() public function register()
{ {
$this->mergeConfigFrom(__DIR__ . '/../config/websockets.php', 'websockets'); $this->mergeConfigFrom(__DIR__.'/../config/websockets.php', 'websockets');
$this->app->singleton('websockets.router', function () { $this->app->singleton('websockets.router', function () {
return new Router(); return new Router();
@ -63,15 +61,15 @@ class WebSocketsServiceProvider extends ServiceProvider
protected function registerRoutes() protected function registerRoutes()
{ {
Route::prefix(config('websockets.path'))->group(function() { Route::prefix(config('websockets.path'))->group(function () {
Route::middleware(AuthorizeDashboard::class)->group(function() { Route::middleware(AuthorizeDashboard::class)->group(function () {
Route::get('/', ShowDashboard::class); Route::get('/', ShowDashboard::class);
Route::get('/api/{appId}/statistics', [DashboardApiController::class, 'getStatistics']); Route::get('/api/{appId}/statistics', [DashboardApiController::class, 'getStatistics']);
Route::post('auth', AuthenticateDashboard::class); Route::post('auth', AuthenticateDashboard::class);
Route::post('event', SendMessage::class); Route::post('event', SendMessage::class);
}); });
Route::middleware(AuthorizeStatistics::class)->group(function() { Route::middleware(AuthorizeStatistics::class)->group(function () {
Route::post('statistics', [WebSocketStatisticsEntriesController::class, 'store']); Route::post('statistics', [WebSocketStatisticsEntriesController::class, 'store']);
}); });
}); });

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebsockets\Tests\Channels; namespace BeyondCode\LaravelWebsockets\Tests\Channels;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
class ChannelTest extends TestCase class ChannelTest extends TestCase
{ {
@ -15,7 +15,7 @@ class ChannelTest extends TestCase
$message = new Message(json_encode([ $message = new Message(json_encode([
'event' => 'pusher:subscribe', 'event' => 'pusher:subscribe',
'data' => [ 'data' => [
'channel' => 'basic-channel' 'channel' => 'basic-channel',
], ],
])); ]));
@ -24,7 +24,7 @@ class ChannelTest extends TestCase
$this->pusherServer->onMessage($connection, $message); $this->pusherServer->onMessage($connection, $message);
$connection->assertSentEvent('pusher_internal:subscription_succeeded', [ $connection->assertSentEvent('pusher_internal:subscription_succeeded', [
'channel' => 'basic-channel' 'channel' => 'basic-channel',
]); ]);
} }
@ -40,7 +40,7 @@ class ChannelTest extends TestCase
$message = new Message(json_encode([ $message = new Message(json_encode([
'event' => 'pusher:unsubscribe', 'event' => 'pusher:unsubscribe',
'data' => [ 'data' => [
'channel' => 'test-channel' 'channel' => 'test-channel',
], ],
])); ]));
@ -108,7 +108,7 @@ class ChannelTest extends TestCase
$channel->broadcast([ $channel->broadcast([
'event' => 'broadcasted-event', 'event' => 'broadcasted-event',
'channel' => 'test-channel' 'channel' => 'test-channel',
]); ]);
$connection1->assertSentEvent('broadcasted-event'); $connection1->assertSentEvent('broadcasted-event');
@ -125,7 +125,7 @@ class ChannelTest extends TestCase
$channel->broadcastToOthers($connection1, [ $channel->broadcastToOthers($connection1, [
'event' => 'broadcasted-event', 'event' => 'broadcasted-event',
'channel' => 'test-channel' 'channel' => 'test-channel',
]); ]);
$connection1->assertNotSentEvent('broadcasted-event'); $connection1->assertNotSentEvent('broadcasted-event');
@ -145,4 +145,4 @@ class ChannelTest extends TestCase
$connection->assertSentEvent('pusher:pong'); $connection->assertSentEvent('pusher:pong');
} }
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebsockets\Tests\Channels; namespace BeyondCode\LaravelWebsockets\Tests\Channels;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature; use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature;
class PresenceChannelTest extends TestCase class PresenceChannelTest extends TestCase
@ -19,7 +19,7 @@ class PresenceChannelTest extends TestCase
'event' => 'pusher:subscribe', 'event' => 'pusher:subscribe',
'data' => [ 'data' => [
'auth' => 'invalid', 'auth' => 'invalid',
'channel' => 'presence-channel' 'channel' => 'presence-channel',
], ],
])); ]));
@ -38,8 +38,8 @@ class PresenceChannelTest extends TestCase
$channelData = [ $channelData = [
'user_id' => 1, 'user_id' => 1,
'user_info' => [ 'user_info' => [
'name' => 'Marcel' 'name' => 'Marcel',
] ],
]; ];
$signature = "{$connection->socketId}:presence-channel:".json_encode($channelData); $signature = "{$connection->socketId}:presence-channel:".json_encode($channelData);
@ -49,7 +49,7 @@ class PresenceChannelTest extends TestCase
'data' => [ 'data' => [
'auth' => $connection->app->key.':'.hash_hmac('sha256', $signature, $connection->app->secret), 'auth' => $connection->app->key.':'.hash_hmac('sha256', $signature, $connection->app->secret),
'channel' => 'presence-channel', 'channel' => 'presence-channel',
'channel_data' => json_encode($channelData) 'channel_data' => json_encode($channelData),
], ],
])); ]));
@ -59,4 +59,4 @@ class PresenceChannelTest extends TestCase
'channel' => 'presence-channel', 'channel' => 'presence-channel',
]); ]);
} }
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebsockets\Tests\Channels; namespace BeyondCode\LaravelWebsockets\Tests\Channels;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature; use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\InvalidSignature;
class PrivateChannelTest extends TestCase class PrivateChannelTest extends TestCase
@ -19,7 +19,7 @@ class PrivateChannelTest extends TestCase
'event' => 'pusher:subscribe', 'event' => 'pusher:subscribe',
'data' => [ 'data' => [
'auth' => 'invalid', 'auth' => 'invalid',
'channel' => 'private-channel' 'channel' => 'private-channel',
], ],
])); ]));
@ -43,14 +43,14 @@ class PrivateChannelTest extends TestCase
'event' => 'pusher:subscribe', 'event' => 'pusher:subscribe',
'data' => [ 'data' => [
'auth' => "{$connection->app->key}:{$hashedAppSecret}", 'auth' => "{$connection->app->key}:{$hashedAppSecret}",
'channel' => 'private-channel' 'channel' => 'private-channel',
], ],
])); ]));
$this->pusherServer->onMessage($connection, $message); $this->pusherServer->onMessage($connection, $message);
$connection->assertSentEvent('pusher_internal:subscription_succeeded', [ $connection->assertSentEvent('pusher_internal:subscription_succeeded', [
'channel' => 'private-channel' 'channel' => 'private-channel',
]); ]);
} }
} }

View File

@ -3,8 +3,8 @@
namespace BeyondCode\LaravelWebSockets\Tests\ClientProviders; namespace BeyondCode\LaravelWebSockets\Tests\ClientProviders;
use BeyondCode\LaravelWebSockets\Apps\App; use BeyondCode\LaravelWebSockets\Apps\App;
use BeyondCode\LaravelWebSockets\Exceptions\InvalidApp;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Exceptions\InvalidApp;
class AppTest extends TestCase class AppTest extends TestCase
{ {
@ -31,4 +31,4 @@ class AppTest extends TestCase
new App(1, 'appKey', '', 'new'); new App(1, 'appKey', '', 'new');
} }
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebSockets\Tests\ClientProviders; namespace BeyondCode\LaravelWebSockets\Tests\ClientProviders;
use BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider;
class ConfigAppProviderTest extends TestCase class ConfigAppProviderTest extends TestCase
{ {
@ -24,7 +24,7 @@ class ConfigAppProviderTest extends TestCase
$this->assertCount(1, $apps); $this->assertCount(1, $apps);
/** @var $app */ /** @var $app */
$app = $apps[0]; $app = $apps[0];
$this->assertEquals('Test App', $app->name); $this->assertEquals('Test App', $app->name);
@ -85,4 +85,4 @@ class ConfigAppProviderTest extends TestCase
$this->assertFalse($app->clientMessagesEnabled); $this->assertFalse($app->clientMessagesEnabled);
$this->assertTrue($app->statisticsEnabled); $this->assertTrue($app->statisticsEnabled);
} }
} }

View File

@ -3,14 +3,13 @@
namespace BeyondCode\LaravelWebSockets\Tests\Commands; namespace BeyondCode\LaravelWebSockets\Tests\Commands;
use Artisan; use Artisan;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
use Carbon\Carbon; use Carbon\Carbon;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
class CleanStatisticsTest extends TestCase class CleanStatisticsTest extends TestCase
{ {
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
@ -20,7 +19,6 @@ class CleanStatisticsTest extends TestCase
$this->app['config']->set('websockets.statistics.delete_statistics_older_than_days', 31); $this->app['config']->set('websockets.statistics.delete_statistics_older_than_days', 31);
} }
/** @test */ /** @test */
public function it_can_clean_the_statistics() public function it_can_clean_the_statistics()
{ {
@ -44,4 +42,4 @@ class CleanStatisticsTest extends TestCase
$this->assertCount(0, WebSocketsStatisticsEntry::where('created_at', '<', $cutOffDate)->get()); $this->assertCount(0, WebSocketsStatisticsEntry::where('created_at', '<', $cutOffDate)->get());
} }
} }

View File

@ -3,12 +3,11 @@
namespace BeyondCode\LaravelWebSockets\Tests; namespace BeyondCode\LaravelWebSockets\Tests;
use BeyondCode\LaravelWebSockets\Apps\App; use BeyondCode\LaravelWebSockets\Apps\App;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message; use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey;
class ConnectionTest extends TestCase class ConnectionTest extends TestCase
{ {
/** @test */ /** @test */
public function unknown_app_keys_can_not_connect() public function unknown_app_keys_can_not_connect()
{ {
@ -54,4 +53,4 @@ class ConnectionTest extends TestCase
$connection->assertSentEvent('pusher:pong'); $connection->assertSentEvent('pusher:pong');
} }
} }

View File

@ -2,16 +2,15 @@
namespace BeyondCode\LaravelWebSockets\Tests\HttpApi; namespace BeyondCode\LaravelWebSockets\Tests\HttpApi;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelController;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Request;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelController;
class FetchChannelTest extends TestCase class FetchChannelTest extends TestCase
{ {
/** @test */ /** @test */
public function invalid_signatures_can_not_access_the_api() public function invalid_signatures_can_not_access_the_api()
{ {
@ -24,12 +23,12 @@ class FetchChannelTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channels\n" . "GET\n/apps/1234/channels\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'InvalidSecret'); $auth_signature = hash_hmac('sha256', $signature, 'InvalidSecret');
@ -53,12 +52,12 @@ class FetchChannelTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channel/my-channel\n" . "GET\n/apps/1234/channel/my-channel\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'TestSecret'); $auth_signature = hash_hmac('sha256', $signature, 'TestSecret');
@ -74,7 +73,7 @@ class FetchChannelTest extends TestCase
$this->assertSame([ $this->assertSame([
'occupied' => true, 'occupied' => true,
'subscription_count' => 2 'subscription_count' => 2,
], json_decode($response->getContent(), true)); ], json_decode($response->getContent(), true));
} }
@ -92,12 +91,12 @@ class FetchChannelTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channel/my-channel\n" . "GET\n/apps/1234/channel/my-channel\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'TestSecret'); $auth_signature = hash_hmac('sha256', $signature, 'TestSecret');
@ -113,8 +112,7 @@ class FetchChannelTest extends TestCase
$this->assertSame([ $this->assertSame([
'occupied' => true, 'occupied' => true,
'subscription_count' => 2 'subscription_count' => 2,
], json_decode($response->getContent(), true)); ], json_decode($response->getContent(), true));
} }
}
}

View File

@ -2,17 +2,15 @@
namespace BeyondCode\LaravelWebSockets\Tests\HttpApi; namespace BeyondCode\LaravelWebSockets\Tests\HttpApi;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelsController;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Request;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelsController;
class FetchChannelsTest extends TestCase class FetchChannelsTest extends TestCase
{ {
/** @test */ /** @test */
public function invalid_signatures_can_not_access_the_api() public function invalid_signatures_can_not_access_the_api()
{ {
@ -25,12 +23,12 @@ class FetchChannelsTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channels\n" . "GET\n/apps/1234/channels\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'InvalidSecret'); $auth_signature = hash_hmac('sha256', $signature, 'InvalidSecret');
@ -55,12 +53,12 @@ class FetchChannelsTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channels\n" . "GET\n/apps/1234/channels\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'TestSecret'); $auth_signature = hash_hmac('sha256', $signature, 'TestSecret');
@ -77,10 +75,9 @@ class FetchChannelsTest extends TestCase
$this->assertSame([ $this->assertSame([
'channels' => [ 'channels' => [
'presence-channel' => [ 'presence-channel' => [
'user_count' => 3 'user_count' => 3,
] ],
] ],
], json_decode($response->getContent(), true)); ], json_decode($response->getContent(), true));
} }
}
}

View File

@ -2,17 +2,14 @@
namespace BeyondCode\LaravelWebSockets\Tests\HttpApi; namespace BeyondCode\LaravelWebSockets\Tests\HttpApi;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchChannelController;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchUsersController;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use BeyondCode\LaravelWebSockets\Tests\TestCase;
use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Request;
use Illuminate\Http\JsonResponse; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use BeyondCode\LaravelWebSockets\HttpApi\Controllers\FetchUsersController;
class FetchUsersTest extends TestCase class FetchUsersTest extends TestCase
{ {
/** @test */ /** @test */
public function invalid_signatures_can_not_access_the_api() public function invalid_signatures_can_not_access_the_api()
{ {
@ -25,12 +22,12 @@ class FetchUsersTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channels\n" . "GET\n/apps/1234/channels\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'InvalidSecret'); $auth_signature = hash_hmac('sha256', $signature, 'InvalidSecret');
@ -56,12 +53,12 @@ class FetchUsersTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channel/my-channel/users\n" . "GET\n/apps/1234/channel/my-channel/users\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'TestSecret'); $auth_signature = hash_hmac('sha256', $signature, 'TestSecret');
@ -87,12 +84,12 @@ class FetchUsersTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channel/my-channel/users\n" . "GET\n/apps/1234/channel/my-channel/users\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'TestSecret'); $auth_signature = hash_hmac('sha256', $signature, 'TestSecret');
@ -115,12 +112,12 @@ class FetchUsersTest extends TestCase
$auth_timestamp = time(); $auth_timestamp = time();
$auth_version = '1.0'; $auth_version = '1.0';
$queryParameters = http_build_query(compact('auth_key','auth_timestamp','auth_version')); $queryParameters = http_build_query(compact('auth_key', 'auth_timestamp', 'auth_version'));
$signature = $signature =
"GET\n/apps/1234/channel/my-channel/users\n" . "GET\n/apps/1234/channel/my-channel/users\n".
"auth_key={$auth_key}" . "auth_key={$auth_key}".
"&auth_timestamp={$auth_timestamp}" . "&auth_timestamp={$auth_timestamp}".
"&auth_version={$auth_version}"; "&auth_version={$auth_version}";
$auth_signature = hash_hmac('sha256', $signature, 'TestSecret'); $auth_signature = hash_hmac('sha256', $signature, 'TestSecret');
@ -137,9 +134,9 @@ class FetchUsersTest extends TestCase
$this->assertSame([ $this->assertSame([
'users' => [ 'users' => [
[ [
'id' => 1 'id' => 1,
] ],
] ],
], json_decode($response->getContent(), true)); ], json_decode($response->getContent(), true));
} }
} }

View File

@ -16,7 +16,7 @@ class PusherClientMessageTest extends TestCase
'event' => 'client-test', 'event' => 'client-test',
'channel' => 'test-channel', 'channel' => 'test-channel',
'data' => [ 'data' => [
'client-event' => 'test' 'client-event' => 'test',
], ],
])); ]));
@ -46,7 +46,7 @@ class PusherClientMessageTest extends TestCase
'event' => 'client-test', 'event' => 'client-test',
'channel' => 'test-channel', 'channel' => 'test-channel',
'data' => [ 'data' => [
'client-event' => 'test' 'client-event' => 'test',
], ],
])); ]));
@ -56,8 +56,8 @@ class PusherClientMessageTest extends TestCase
$connection2->assertSentEvent('client-test', [ $connection2->assertSentEvent('client-test', [
'data' => [ 'data' => [
'client-event' => 'test' 'client-event' => 'test',
] ],
]); ]);
} }
} }

View File

@ -54,4 +54,4 @@ class Connection implements ConnectionInterface
{ {
PHPUnit::assertTrue($this->closed); PHPUnit::assertTrue($this->closed);
} }
} }

View File

@ -2,7 +2,6 @@
namespace BeyondCode\LaravelWebSockets\Tests\Mocks; namespace BeyondCode\LaravelWebSockets\Tests\Mocks;
class Message extends \Ratchet\RFC6455\Messaging\Message class Message extends \Ratchet\RFC6455\Messaging\Message
{ {
protected $payload; protected $payload;
@ -16,4 +15,4 @@ class Message extends \Ratchet\RFC6455\Messaging\Message
{ {
return $this->payload; return $this->payload;
} }
} }

View File

@ -2,9 +2,9 @@
namespace BeyondCode\LaravelWebSockets\Tests\Statistics\Controllers; namespace BeyondCode\LaravelWebSockets\Tests\Statistics\Controllers;
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry;
use BeyondCode\LaravelWebSockets\Statistics\Http\Controllers\WebSocketStatisticsEntriesController;
class WebSocketsStatisticsControllerTest extends TestCase class WebSocketsStatisticsControllerTest extends TestCase
{ {
@ -34,4 +34,4 @@ class WebSocketsStatisticsControllerTest extends TestCase
'api_message_count' => 3, 'api_message_count' => 3,
]; ];
} }
} }

View File

@ -2,8 +2,8 @@
namespace BeyondCode\LaravelWebSockets\Tests\Statistics\Rules; namespace BeyondCode\LaravelWebSockets\Tests\Statistics\Rules;
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
use BeyondCode\LaravelWebSockets\Tests\TestCase; use BeyondCode\LaravelWebSockets\Tests\TestCase;
use BeyondCode\LaravelWebSockets\Statistics\Rules\AppId;
class AppIdTest extends TestCase class AppIdTest extends TestCase
{ {
@ -15,4 +15,4 @@ class AppIdTest extends TestCase
$this->assertTrue($rule->passes('app_id', config('websockets.apps.0.id'))); $this->assertTrue($rule->passes('app_id', config('websockets.apps.0.id')));
$this->assertFalse($rule->passes('app_id', 'invalid-app-id')); $this->assertFalse($rule->passes('app_id', 'invalid-app-id'));
} }
} }

View File

@ -2,16 +2,14 @@
namespace BeyondCode\LaravelWebSockets\Tests; namespace BeyondCode\LaravelWebSockets\Tests;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Request;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use BeyondCode\LaravelWebSockets\WebSocketsServiceProvider;
use Illuminate\Support\Facades\Route;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Message;
use BeyondCode\LaravelWebSockets\Tests\Mocks\Connection;
use BeyondCode\LaravelWebSockets\Facades\StatisticsLogger;
use BeyondCode\LaravelWebSockets\WebSocketsServiceProvider;
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler;
use BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManager;
abstract class TestCase extends \Orchestra\Testbench\TestCase abstract class TestCase extends \Orchestra\Testbench\TestCase
{ {
@ -53,8 +51,6 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
include_once __DIR__.'/../database/migrations/create_websockets_statistics_entries_table.php.stub'; include_once __DIR__.'/../database/migrations/create_websockets_statistics_entries_table.php.stub';
(new \CreateWebSocketsStatisticsEntriesTable())->up(); (new \CreateWebSocketsStatisticsEntriesTable())->up();
} }
protected function getWebSocketConnection(string $url = '/?appKey=TestKey'): Connection protected function getWebSocketConnection(string $url = '/?appKey=TestKey'): Connection
@ -78,7 +74,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
$message = new Message(json_encode([ $message = new Message(json_encode([
'event' => 'pusher:subscribe', 'event' => 'pusher:subscribe',
'data' => [ 'data' => [
'channel' => $channel 'channel' => $channel,
], ],
])); ]));
@ -97,8 +93,8 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
$channelData = [ $channelData = [
'user_id' => 1, 'user_id' => 1,
'user_info' => [ 'user_info' => [
'name' => 'Marcel' 'name' => 'Marcel',
] ],
]; ];
$signature = "{$connection->socketId}:{$channel}:".json_encode($channelData); $signature = "{$connection->socketId}:{$channel}:".json_encode($channelData);
@ -108,7 +104,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
'data' => [ 'data' => [
'auth' => $connection->app->key.':'.hash_hmac('sha256', $signature, $connection->app->secret), 'auth' => $connection->app->key.':'.hash_hmac('sha256', $signature, $connection->app->secret),
'channel' => $channel, 'channel' => $channel,
'channel_data' => json_encode($channelData) 'channel_data' => json_encode($channelData),
], ],
])); ]));
@ -126,4 +122,4 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
{ {
$this->assertTrue(true); $this->assertTrue(true);
} }
} }