2025-01-16 07:54:02 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
namespace BlaxSoftware\LaravelWebSockets\Websocket;
|
|
|
|
|
|
|
|
|
|
use BlaxSoftware\LaravelWebSockets\ChannelManagers\LocalChannelManager;
|
|
|
|
|
use BlaxSoftware\LaravelWebSockets\Channels\Channel;
|
|
|
|
|
use BlaxSoftware\LaravelWebSockets\Channels\PresenceChannel;
|
|
|
|
|
use BlaxSoftware\LaravelWebSockets\Channels\PrivateChannel;
|
2026-03-23 13:13:30 +00:00
|
|
|
use Illuminate\Support\Facades\Auth;
|
2025-01-17 09:45:53 +00:00
|
|
|
use Illuminate\Support\Facades\Log;
|
2026-03-23 13:13:30 +00:00
|
|
|
use Ratchet\ConnectionInterface;
|
2025-01-16 07:54:02 +00:00
|
|
|
|
|
|
|
|
class Controller
|
|
|
|
|
{
|
2025-12-05 21:08:47 +00:00
|
|
|
protected bool $isMockConnection;
|
|
|
|
|
|
2025-01-16 07:54:02 +00:00
|
|
|
final public function __construct(
|
|
|
|
|
protected ConnectionInterface $connection,
|
|
|
|
|
protected PrivateChannel|Channel|PresenceChannel|null $channel,
|
|
|
|
|
protected string $event,
|
2026-04-02 10:44:16 +00:00
|
|
|
protected LocalChannelManager $channelManager
|
2025-12-05 21:08:47 +00:00
|
|
|
) {
|
2026-02-09 12:19:09 +00:00
|
|
|
$this->isMockConnection = $connection instanceof MockConnectionSocketPair;
|
2025-12-05 21:08:47 +00:00
|
|
|
}
|
2025-01-16 07:54:02 +00:00
|
|
|
|
2025-12-17 20:34:20 +00:00
|
|
|
/**
|
|
|
|
|
* To be overridden by child classes if needed
|
|
|
|
|
* Called before need_auth check
|
2025-12-18 08:29:34 +00:00
|
|
|
* If return is exactly false, processing stops
|
2025-12-17 20:34:20 +00:00
|
|
|
*
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
2025-12-18 08:29:34 +00:00
|
|
|
public function boot() {}
|
2025-12-17 20:34:20 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* To be overridden by child classes if needed
|
|
|
|
|
* Called after need_auth check
|
2025-12-18 08:29:34 +00:00
|
|
|
* If return is exactly false, processing stops
|
2025-12-17 20:34:20 +00:00
|
|
|
*
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
2025-12-18 08:29:34 +00:00
|
|
|
public function booted() {}
|
2025-12-17 20:34:20 +00:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* To be overridden by child classes if needed
|
|
|
|
|
* Called after main function execution (even if not found)
|
|
|
|
|
*
|
|
|
|
|
* @return void
|
|
|
|
|
*/
|
|
|
|
|
public function unboot(): void {}
|
|
|
|
|
|
2026-08-06 08:42:34 +00:00
|
|
|
/**
|
|
|
|
|
* Shared platform-maintenance flag, read from the same DB-cache key the host
|
|
|
|
|
* app writes via App\Support\Maintenance::CACHE_KEY. Hardcoded (not config)
|
|
|
|
|
* to dodge the fork-child package-config-merge gap, and wrapped so a cache
|
|
|
|
|
* hiccup can never wedge the socket. Keep the key string in sync with the app.
|
|
|
|
|
*/
|
|
|
|
|
protected static function maintenanceActive(): bool
|
|
|
|
|
{
|
|
|
|
|
try {
|
|
|
|
|
return (bool) cache()->get('platform:maintenance', false);
|
|
|
|
|
} catch (\Throwable) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected static function maintenanceMessage(): string
|
|
|
|
|
{
|
|
|
|
|
try {
|
|
|
|
|
$message = cache()->get('platform:maintenance:message');
|
|
|
|
|
} catch (\Throwable) {
|
|
|
|
|
$message = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return is_string($message) && $message !== ''
|
|
|
|
|
? $message
|
|
|
|
|
: 'We are performing scheduled maintenance and will be back shortly.';
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-16 07:54:02 +00:00
|
|
|
public static function controll_message(
|
|
|
|
|
ConnectionInterface $connection,
|
2025-09-14 13:00:27 +00:00
|
|
|
PrivateChannel|Channel|PresenceChannel $channel,
|
2025-01-16 07:54:02 +00:00
|
|
|
array $message,
|
2026-04-02 10:44:16 +00:00
|
|
|
LocalChannelManager $channelManager
|
2025-01-16 07:54:02 +00:00
|
|
|
) {
|
|
|
|
|
$event = self::get_event($message);
|
2026-04-16 07:02:25 +00:00
|
|
|
|
|
|
|
|
// Introspection: single-part event like "auth" or "websocket"
|
|
|
|
|
if (count($event) === 1) {
|
|
|
|
|
return self::handleIntrospection($connection, $message, $event[0]);
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
if (count($event) !== 2) {
|
|
|
|
|
return self::send_error($connection, $message, 'Event unknown');
|
2025-01-16 07:54:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2026-01-24 13:42:35 +00:00
|
|
|
$eventPrefix = $event[0];
|
2025-01-16 07:54:02 +00:00
|
|
|
$method = static::without_uniquifyer($event[1]);
|
|
|
|
|
|
2026-01-24 13:42:35 +00:00
|
|
|
// Use cached controller resolver for fast lookup
|
|
|
|
|
$controllerClass = ControllerResolver::resolve($eventPrefix);
|
2025-12-05 21:08:47 +00:00
|
|
|
|
|
|
|
|
if (! $controllerClass) {
|
2026-04-29 06:29:49 +00:00
|
|
|
// Fallback: an HTTP controller method tagged with the
|
|
|
|
|
// #[Websocket] attribute may handle this event. The registry
|
|
|
|
|
// exposes a flat event-name → callable map built by
|
|
|
|
|
// reflecting attribute-tagged methods at scan time.
|
2026-04-29 07:26:53 +00:00
|
|
|
//
|
|
|
|
|
// IMPORTANT: registry keys are stored without the client-side
|
|
|
|
|
// `[uniquifier]` segment (e.g. `flightschool.index[abc123]`),
|
|
|
|
|
// so we rebuild the lookup name from the cleaned prefix +
|
|
|
|
|
// cleaned method instead of using `$message['event']` raw.
|
|
|
|
|
$cleanEvent = $eventPrefix . '.' . $method;
|
|
|
|
|
$target = EventRegistry::resolve($cleanEvent);
|
2026-04-29 06:29:49 +00:00
|
|
|
if ($target) {
|
|
|
|
|
return self::dispatchHttpAttributeTarget($connection, $message, $target);
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
return self::send_error($connection, $message, 'Event could not be associated');
|
2025-01-16 07:54:02 +00:00
|
|
|
}
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
$controller = new $controllerClass(
|
2025-01-16 07:54:02 +00:00
|
|
|
$connection,
|
|
|
|
|
$channel,
|
|
|
|
|
$message['event'],
|
|
|
|
|
$channelManager
|
2025-12-05 21:08:47 +00:00
|
|
|
);
|
2025-01-16 07:54:02 +00:00
|
|
|
|
2025-12-18 08:29:34 +00:00
|
|
|
if ($controller->boot() === false) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-12-17 20:34:20 +00:00
|
|
|
|
2025-01-16 07:54:02 +00:00
|
|
|
if (($controller->need_auth ?? true) && ! $connection->user) {
|
2026-03-23 13:13:30 +00:00
|
|
|
// Self-heal: the parent process may have a stale DB connection that
|
|
|
|
|
// can't find newly created tokens. The child process has a fresh DB
|
|
|
|
|
// connection (reconnected after fork), so try to authenticate here.
|
|
|
|
|
$authtoken = @$message['data']['authtoken'] ?? null;
|
|
|
|
|
if ($authtoken) {
|
|
|
|
|
try {
|
2026-04-17 09:03:02 +00:00
|
|
|
$resolved = self::resolveUserFromToken($authtoken);
|
|
|
|
|
if ($resolved) {
|
|
|
|
|
$connection->user = $resolved;
|
2026-03-23 13:13:30 +00:00
|
|
|
Auth::login($connection->user);
|
|
|
|
|
// Clear parent's stale auth cache so it re-authenticates
|
|
|
|
|
if ($connection instanceof MockConnectionSocketPair) {
|
|
|
|
|
$connection->clearConnectionData('authLoaded');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
// Auth self-heal failed, fall through to Unauthorized
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (! $connection->user) {
|
|
|
|
|
$controller->error('Unauthorized');
|
|
|
|
|
$controller->unboot();
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-01-16 07:54:02 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-06 08:42:34 +00:00
|
|
|
// Platform maintenance freeze. Once auth (incl. the self-heal above)
|
|
|
|
|
// has resolved the user, refuse every controller event for non-admins
|
|
|
|
|
// so a deploy/migration can run without clients mutating state. Admins
|
|
|
|
|
// bypass to smoke-test. The `auth` handshake + channel introspection
|
|
|
|
|
// are single-part events handled earlier, so a maintainer can still
|
|
|
|
|
// authenticate to obtain the bypass.
|
|
|
|
|
if (self::maintenanceActive() && ! ($connection->user?->is_admin ?? false)) {
|
|
|
|
|
$controller->error([
|
|
|
|
|
'message' => self::maintenanceMessage(),
|
|
|
|
|
'maintenance' => true,
|
|
|
|
|
]);
|
|
|
|
|
$controller->unboot();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-17 20:34:20 +00:00
|
|
|
if (! method_exists($controllerClass, $method)) {
|
2026-02-10 13:05:36 +00:00
|
|
|
$controller->error('Event could not be handled');
|
2025-12-17 20:34:20 +00:00
|
|
|
$controller->unboot();
|
2025-12-18 08:29:34 +00:00
|
|
|
return;
|
2025-12-17 20:34:20 +00:00
|
|
|
}
|
|
|
|
|
|
2025-12-18 08:29:34 +00:00
|
|
|
if ($controller->booted() === false) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-12-17 20:34:20 +00:00
|
|
|
|
2025-01-16 07:54:02 +00:00
|
|
|
$payload = $controller->$method(
|
|
|
|
|
$connection,
|
2025-06-18 09:02:39 +00:00
|
|
|
@$message['data'] ?? [],
|
2025-01-16 07:54:02 +00:00
|
|
|
$message['channel']
|
|
|
|
|
);
|
|
|
|
|
|
2025-12-17 20:34:20 +00:00
|
|
|
$controller->unboot();
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
if ($payload === false || $payload === true) {
|
|
|
|
|
return null;
|
2025-01-16 07:54:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$connection->send(json_encode([
|
|
|
|
|
'event' => $message['event'] . ':response',
|
|
|
|
|
'data' => $payload,
|
|
|
|
|
'channel' => $message['channel'],
|
|
|
|
|
]));
|
|
|
|
|
|
|
|
|
|
return $payload;
|
2025-09-06 08:43:07 +00:00
|
|
|
} catch (\Throwable $e) {
|
2026-11-20 10:35:32 +00:00
|
|
|
$data = @$message['data'];
|
|
|
|
|
// The client's bearer token rides in every message; logs and error trackers
|
|
|
|
|
// must never hold it.
|
|
|
|
|
if (is_array($data)) {
|
|
|
|
|
unset($data['authtoken']);
|
|
|
|
|
}
|
2025-01-16 07:54:02 +00:00
|
|
|
$reload = [
|
|
|
|
|
'event' => @$message['event'],
|
2026-11-20 10:35:32 +00:00
|
|
|
'data' => $data,
|
2025-01-16 07:54:02 +00:00
|
|
|
'channel' => @$message['channel'],
|
|
|
|
|
'line' => $e->getFile() . ':' . $e->getLine(),
|
2025-09-07 06:58:09 +00:00
|
|
|
'stack' => $e->getTraceAsString(),
|
2025-01-16 07:54:02 +00:00
|
|
|
];
|
|
|
|
|
|
2026-05-03 08:33:58 +00:00
|
|
|
$isValidation = $e instanceof \Illuminate\Validation\ValidationException;
|
|
|
|
|
|
|
|
|
|
if ($isValidation) {
|
|
|
|
|
Log::info('WS validation failed: ' . $e->getMessage(), $reload);
|
|
|
|
|
} else {
|
|
|
|
|
Log::error($e->getMessage(), $reload);
|
|
|
|
|
|
|
|
|
|
if (app()->bound('sentry')) {
|
|
|
|
|
app('sentry')->captureException($e);
|
|
|
|
|
}
|
2025-12-05 21:08:47 +00:00
|
|
|
}
|
2025-01-16 07:54:02 +00:00
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
return self::send_error($connection, $message, $e->getMessage(), true);
|
|
|
|
|
}
|
2025-01-16 07:54:02 +00:00
|
|
|
}
|
|
|
|
|
|
2026-04-29 06:29:49 +00:00
|
|
|
/**
|
|
|
|
|
* Dispatch an event whose target is an HTTP controller method tagged
|
|
|
|
|
* with the {@see \BlaxSoftware\LaravelWebSockets\Attributes\Websocket}
|
|
|
|
|
* attribute (resolved via {@see EventRegistry}).
|
|
|
|
|
*
|
|
|
|
|
* HTTP controllers don't accept the WS-specific constructor args
|
|
|
|
|
* ($connection, $channel, $event, $channelManager), so we resolve them
|
|
|
|
|
* through the Laravel container and shape the call to look like a
|
|
|
|
|
* normal HTTP invocation:
|
|
|
|
|
*
|
|
|
|
|
* - request()->merge($data) so `request('foo')` works
|
|
|
|
|
* - method positional args resolved by name from $data
|
|
|
|
|
* - JsonResponse/Response payloads unwrapped to plain data
|
|
|
|
|
*
|
|
|
|
|
* Auth gating mirrors the standard flow: `needAuth` enforces an
|
|
|
|
|
* authenticated $connection->user, with the same self-heal hop via
|
|
|
|
|
* the auth token if the parent process didn't see it.
|
|
|
|
|
*
|
|
|
|
|
* @param array{class: class-string, method: string, needAuth: bool} $target
|
|
|
|
|
*/
|
|
|
|
|
protected static function dispatchHttpAttributeTarget(
|
|
|
|
|
ConnectionInterface $connection,
|
|
|
|
|
array $message,
|
|
|
|
|
array $target
|
|
|
|
|
) {
|
|
|
|
|
if ($target['needAuth'] && ! ($connection->user ?? null)) {
|
|
|
|
|
$authtoken = @$message['data']['authtoken'] ?? null;
|
|
|
|
|
if ($authtoken) {
|
|
|
|
|
try {
|
|
|
|
|
$resolved = self::resolveUserFromToken($authtoken);
|
|
|
|
|
if ($resolved) {
|
|
|
|
|
$connection->user = $resolved;
|
|
|
|
|
Auth::login($connection->user);
|
|
|
|
|
}
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
// self-heal failed; fall through to the unauthorized branch
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (! ($connection->user ?? null)) {
|
|
|
|
|
return self::send_error($connection, $message, 'Unauthorized');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$data = is_array($message['data'] ?? null) ? $message['data'] : [];
|
|
|
|
|
|
|
|
|
|
// Make WS data visible to anything that calls `request()`.
|
|
|
|
|
try {
|
|
|
|
|
request()->merge($data);
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
// request() not bound — shouldn't happen in a Laravel app, ignore.
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$instance = app($target['class']);
|
|
|
|
|
$args = self::resolveAttributeMethodArgs($target['class'], $target['method'], $data);
|
|
|
|
|
|
|
|
|
|
$payload = $instance->{$target['method']}(...$args);
|
|
|
|
|
|
|
|
|
|
// Normalize Response/JsonResponse → plain data
|
|
|
|
|
if ($payload instanceof \Illuminate\Http\JsonResponse) {
|
|
|
|
|
$payload = $payload->getData(true);
|
|
|
|
|
} elseif ($payload instanceof \Symfony\Component\HttpFoundation\Response) {
|
|
|
|
|
$decoded = json_decode($payload->getContent() ?: 'null', true);
|
|
|
|
|
$payload = (json_last_error() === JSON_ERROR_NONE) ? $decoded : $payload->getContent();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$connection->send(json_encode([
|
|
|
|
|
'event' => $message['event'] . ':response',
|
|
|
|
|
'data' => $payload,
|
|
|
|
|
'channel' => $message['channel'] ?? null,
|
|
|
|
|
]));
|
|
|
|
|
|
|
|
|
|
return $payload;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Reflect the target method and pull positional args by parameter name
|
|
|
|
|
* from the WS payload. This mirrors how Laravel's HTTP route bindings
|
|
|
|
|
* pass URL segments to controller methods (e.g. `show(string $slug)`
|
|
|
|
|
* gets the `slug` value from $data['slug']).
|
|
|
|
|
*
|
|
|
|
|
* Falls through to default values, then null for nullable params.
|
|
|
|
|
*
|
|
|
|
|
* @return array<int, mixed>
|
|
|
|
|
*/
|
|
|
|
|
protected static function resolveAttributeMethodArgs(string $class, string $method, array $data): array
|
|
|
|
|
{
|
|
|
|
|
try {
|
|
|
|
|
$reflection = new \ReflectionMethod($class, $method);
|
|
|
|
|
} catch (\Throwable) {
|
|
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$args = [];
|
|
|
|
|
foreach ($reflection->getParameters() as $param) {
|
|
|
|
|
$name = $param->getName();
|
|
|
|
|
if (array_key_exists($name, $data)) {
|
|
|
|
|
$args[] = $data[$name];
|
|
|
|
|
} elseif ($param->isDefaultValueAvailable()) {
|
|
|
|
|
$args[] = $param->getDefaultValue();
|
|
|
|
|
} elseif ($param->allowsNull()) {
|
|
|
|
|
$args[] = null;
|
|
|
|
|
} else {
|
|
|
|
|
// Required scalar with no value provided — leave the
|
|
|
|
|
// method to throw/validate so the error reaches the client.
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $args;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-17 09:03:02 +00:00
|
|
|
/**
|
|
|
|
|
* Resolve a user from an authtoken string. First tries the configured
|
|
|
|
|
* `websockets.auth_resolver` callable; falls back to Laravel Sanctum's
|
|
|
|
|
* `PersonalAccessToken::findToken()` if the class exists.
|
|
|
|
|
*
|
|
|
|
|
* Returns an Authenticatable user or null.
|
|
|
|
|
*/
|
|
|
|
|
protected static function resolveUserFromToken(string $authtoken)
|
|
|
|
|
{
|
|
|
|
|
// 1. Configured resolver (closure or [Class, method])
|
|
|
|
|
$resolver = config('websockets.auth_resolver');
|
|
|
|
|
if ($resolver && is_callable($resolver)) {
|
|
|
|
|
$user = $resolver($authtoken);
|
|
|
|
|
if ($user) {
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 2. Container binding (useful for class-based resolvers)
|
|
|
|
|
if (app()->bound('websockets.auth_resolver')) {
|
|
|
|
|
$bound = app('websockets.auth_resolver');
|
|
|
|
|
if (is_callable($bound)) {
|
|
|
|
|
$user = $bound($authtoken);
|
|
|
|
|
if ($user) {
|
|
|
|
|
return $user;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 3. Fallback to Sanctum if available (string class name to avoid
|
|
|
|
|
// autoload errors when the package isn't installed)
|
|
|
|
|
$sanctumClass = 'Laravel\\Sanctum\\PersonalAccessToken';
|
|
|
|
|
if (class_exists($sanctumClass)) {
|
|
|
|
|
$tokenRecord = $sanctumClass::findToken($authtoken);
|
|
|
|
|
if ($tokenRecord?->tokenable) {
|
|
|
|
|
return $tokenRecord->tokenable;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-20 15:46:13 +00:00
|
|
|
final public function progress(
|
|
|
|
|
mixed $payload = null,
|
|
|
|
|
?string $event = null,
|
|
|
|
|
?string $channel = null
|
2025-12-05 21:08:47 +00:00
|
|
|
): bool {
|
2025-01-20 15:46:13 +00:00
|
|
|
$p = [
|
|
|
|
|
'event' => ($event ?? $this->event) . ':progress',
|
|
|
|
|
'data' => $payload,
|
|
|
|
|
'channel' => $channel ?? $this->channel->getName(),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// if payload only contains key "data"
|
|
|
|
|
if (
|
|
|
|
|
count($p) === 1
|
|
|
|
|
&& isset($payload['data'])
|
|
|
|
|
) {
|
|
|
|
|
$p['data'] = $payload['data'];
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
// Pre-encode once (avoid repeated encoding)
|
|
|
|
|
$encoded = json_encode($p);
|
|
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
$this->connection->send($encoded);
|
2025-01-20 15:46:13 +00:00
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-16 07:54:02 +00:00
|
|
|
final public function success(
|
|
|
|
|
mixed $payload = null,
|
|
|
|
|
?string $event = null,
|
|
|
|
|
?string $channel = null
|
2025-12-05 21:08:47 +00:00
|
|
|
): bool {
|
2025-01-16 07:54:02 +00:00
|
|
|
$p = [
|
|
|
|
|
'event' => ($event ?? $this->event) . ':response',
|
|
|
|
|
'data' => $payload,
|
|
|
|
|
'channel' => $channel ?? $this->channel->getName(),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// if payload only contains key "data"
|
|
|
|
|
if (
|
|
|
|
|
count($p) === 1
|
|
|
|
|
&& isset($payload['data'])
|
|
|
|
|
) {
|
|
|
|
|
$p['data'] = $payload['data'];
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
// Pre-encode once (avoid repeated encoding)
|
|
|
|
|
$encoded = json_encode($p);
|
|
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
$this->connection->send($encoded);
|
2025-01-16 07:54:02 +00:00
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final public function error(
|
|
|
|
|
array|string|null $payload = null,
|
|
|
|
|
?string $event = null,
|
|
|
|
|
?string $channel = null
|
2025-12-05 21:08:47 +00:00
|
|
|
): bool {
|
2025-01-16 07:54:02 +00:00
|
|
|
if (is_string($payload)) {
|
|
|
|
|
$payload = [
|
|
|
|
|
'message' => $payload,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$p = [
|
|
|
|
|
'event' => ($event ?? $this->event) . ':error',
|
|
|
|
|
'data' => $payload,
|
|
|
|
|
'channel' => $channel ?? $this->channel->getName(),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// if payload only contains key "data"
|
|
|
|
|
if (
|
|
|
|
|
count($p) === 1
|
|
|
|
|
&& isset($payload['data'])
|
|
|
|
|
) {
|
|
|
|
|
$p['data'] = $payload['data'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// get line from where this is called from
|
|
|
|
|
$trace = debug_backtrace();
|
|
|
|
|
$p['data']['trace'] = $trace
|
|
|
|
|
? $trace[0]['line']
|
|
|
|
|
: null;
|
|
|
|
|
|
2025-06-13 08:31:59 +00:00
|
|
|
Log::channel('websocket')->error('Send error: ' . @$p['data']['message'], $p);
|
2025-01-16 07:54:02 +00:00
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
$this->connection->send(json_encode($p));
|
2025-01-16 07:54:02 +00:00
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-13 17:48:59 +00:00
|
|
|
final public function broadcast(
|
2025-09-13 17:33:29 +00:00
|
|
|
array|string|null $payload = null,
|
|
|
|
|
?string $event = null,
|
|
|
|
|
?string $channel = null,
|
|
|
|
|
bool $including_self = false
|
2025-12-05 21:08:47 +00:00
|
|
|
) {
|
2025-09-13 17:33:29 +00:00
|
|
|
if (is_string($payload)) {
|
|
|
|
|
$payload = [
|
|
|
|
|
'message' => $payload,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-13 17:48:59 +00:00
|
|
|
$channel ??= ($this->channel ? $this->channel->getName() : null);
|
|
|
|
|
|
2025-09-13 17:33:29 +00:00
|
|
|
$p = [
|
|
|
|
|
'event' => ($event ?? $this->event),
|
|
|
|
|
'data' => $payload,
|
2025-09-13 17:48:59 +00:00
|
|
|
'channel' => $channel,
|
2025-09-13 17:33:29 +00:00
|
|
|
];
|
|
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
if ($this->isMockConnection) {
|
|
|
|
|
$this->connection->broadcast($p, $channel, $including_self);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-09-13 17:48:59 +00:00
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
// Direct broadcast (non-forked context, e.g. testing)
|
|
|
|
|
if (! $channel) {
|
|
|
|
|
$this->error('Channel not found');
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-12-05 21:08:47 +00:00
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
$encoded = json_encode($p);
|
2025-09-13 17:48:59 +00:00
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
foreach ($this->channel->getConnections() as $channel_conection) {
|
|
|
|
|
if ($channel_conection !== $this->connection) {
|
|
|
|
|
$channel_conection->send($encoded);
|
2025-09-13 17:48:59 +00:00
|
|
|
}
|
2026-02-09 12:19:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($including_self) {
|
|
|
|
|
$this->connection->send($encoded);
|
2025-09-13 17:33:29 +00:00
|
|
|
}
|
2025-09-15 12:29:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
final public function whisper(
|
|
|
|
|
array|string|null $payload = null,
|
|
|
|
|
?string $event = null,
|
2026-04-29 12:36:12 +00:00
|
|
|
array $socketIds = [],
|
2025-09-15 12:29:07 +00:00
|
|
|
?string $channel = null
|
2025-12-05 21:08:47 +00:00
|
|
|
) {
|
2026-04-29 12:36:12 +00:00
|
|
|
// PHP 8.x deprecates "optional before required" in parameter
|
|
|
|
|
// lists, so $socketIds is now defaulted. Empty $socketIds is a
|
|
|
|
|
// no-op (the array_flip-based lookup below matches no
|
|
|
|
|
// connections), preserving the existing behavior for callers
|
|
|
|
|
// that intentionally omit it.
|
2025-09-15 12:29:07 +00:00
|
|
|
if (is_string($payload)) {
|
|
|
|
|
$payload = [
|
|
|
|
|
'message' => $payload,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$channel ??= ($this->channel ? $this->channel->getName() : null);
|
|
|
|
|
|
|
|
|
|
$p = [
|
|
|
|
|
'event' => ($event ?? $this->event),
|
|
|
|
|
'data' => $payload,
|
|
|
|
|
'channel' => $channel,
|
|
|
|
|
];
|
2025-09-13 17:33:29 +00:00
|
|
|
|
2026-02-09 12:19:09 +00:00
|
|
|
if ($this->isMockConnection) {
|
|
|
|
|
$this->connection->whisper($p, $socketIds, $channel);
|
|
|
|
|
return;
|
2025-09-15 12:29:07 +00:00
|
|
|
}
|
2026-02-09 12:19:09 +00:00
|
|
|
|
|
|
|
|
// Direct whisper (non-forked context, e.g. testing)
|
|
|
|
|
$encoded = json_encode($p);
|
|
|
|
|
$socketIdLookup = array_flip($socketIds);
|
|
|
|
|
$sentTo = [];
|
|
|
|
|
|
|
|
|
|
$this->channelManager->getLocalConnections()->then(function ($connections) use ($socketIdLookup, $encoded, &$sentTo) {
|
|
|
|
|
foreach ($connections as $connection) {
|
|
|
|
|
if (isset($sentTo[$connection->socketId])) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isset($socketIdLookup[$connection->socketId])) {
|
|
|
|
|
$connection->send($encoded);
|
|
|
|
|
$sentTo[$connection->socketId] = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-09-13 17:33:29 +00:00
|
|
|
}
|
|
|
|
|
|
2026-04-16 07:02:25 +00:00
|
|
|
/**
|
|
|
|
|
* Handle introspection requests (dev-only).
|
|
|
|
|
*
|
|
|
|
|
* - `websocket` → list all controllers and their methods
|
|
|
|
|
* - `auth` → list all methods on AuthController
|
|
|
|
|
*/
|
|
|
|
|
private static function handleIntrospection(
|
|
|
|
|
ConnectionInterface $connection,
|
|
|
|
|
array $message,
|
|
|
|
|
string $prefix
|
|
|
|
|
) {
|
|
|
|
|
// Only allow in local environment or when explicitly enabled
|
|
|
|
|
$allowed = config('websockets.introspection', false)
|
|
|
|
|
|| app()->environment('local');
|
|
|
|
|
|
|
|
|
|
if (! $allowed) {
|
|
|
|
|
return self::send_error($connection, $message, 'Introspection disabled');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$prefix = static::without_uniquifyer($prefix);
|
|
|
|
|
|
|
|
|
|
// Special case: "websocket" lists all controllers
|
|
|
|
|
if ($prefix === 'websocket') {
|
|
|
|
|
$controllers = self::introspectAllControllers();
|
|
|
|
|
$connection->send(json_encode([
|
|
|
|
|
'event' => ($message['event'] ?? 'websocket') . ':response',
|
|
|
|
|
'data' => $controllers,
|
|
|
|
|
'channel' => $message['channel'] ?? null,
|
|
|
|
|
]));
|
|
|
|
|
return $controllers;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Specific controller: "auth" → AuthController
|
|
|
|
|
$controllerClass = ControllerResolver::resolve($prefix);
|
|
|
|
|
if (! $controllerClass) {
|
|
|
|
|
return self::send_error($connection, $message, "No controller found for '{$prefix}'");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$info = self::introspectController($controllerClass, $prefix);
|
|
|
|
|
$connection->send(json_encode([
|
|
|
|
|
'event' => ($message['event'] ?? $prefix) . ':response',
|
|
|
|
|
'data' => $info,
|
|
|
|
|
'channel' => $message['channel'] ?? null,
|
|
|
|
|
]));
|
|
|
|
|
return $info;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Introspect a single controller: list public methods, auth, lifecycle.
|
|
|
|
|
*/
|
|
|
|
|
private static function introspectController(string $controllerClass, string $prefix): array
|
|
|
|
|
{
|
|
|
|
|
$reflection = new \ReflectionClass($controllerClass);
|
|
|
|
|
$needAuth = true;
|
|
|
|
|
|
|
|
|
|
// Check need_auth property
|
|
|
|
|
if ($reflection->hasProperty('need_auth')) {
|
|
|
|
|
$prop = $reflection->getProperty('need_auth');
|
|
|
|
|
$needAuth = $prop->getDefaultValue() ?? true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check lifecycle methods
|
|
|
|
|
$hasBoot = $reflection->getMethod('boot')->getDeclaringClass()->getName() !== self::class;
|
|
|
|
|
$hasBooted = $reflection->getMethod('booted')->getDeclaringClass()->getName() !== self::class;
|
|
|
|
|
$hasUnboot = $reflection->getMethod('unboot')->getDeclaringClass()->getName() !== self::class;
|
|
|
|
|
|
|
|
|
|
// Collect public non-inherited, non-magic methods
|
|
|
|
|
$baseMethods = get_class_methods(self::class);
|
|
|
|
|
$methods = [];
|
|
|
|
|
foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
|
|
|
|
|
$name = $method->getName();
|
|
|
|
|
|
|
|
|
|
// Skip inherited base methods, constructors, and magic methods
|
|
|
|
|
if (in_array($name, $baseMethods, true)) continue;
|
|
|
|
|
if (str_starts_with($name, '__')) continue;
|
|
|
|
|
if ($method->isStatic()) continue;
|
|
|
|
|
|
|
|
|
|
$info = ['name' => $name, 'event' => "{$prefix}.{$name}"];
|
|
|
|
|
|
|
|
|
|
// Add parameter names (skip $connection, $data, $channel)
|
|
|
|
|
$params = [];
|
|
|
|
|
foreach ($method->getParameters() as $i => $param) {
|
|
|
|
|
if ($i < 3) continue; // skip standard ($connection, $data, $channel)
|
|
|
|
|
$params[] = '$' . $param->getName();
|
|
|
|
|
}
|
|
|
|
|
if ($params) $info['extra_params'] = $params;
|
|
|
|
|
|
|
|
|
|
$methods[] = $info;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'controller' => $controllerClass,
|
|
|
|
|
'prefix' => $prefix,
|
|
|
|
|
'need_auth' => $needAuth,
|
|
|
|
|
'lifecycle' => array_filter([
|
|
|
|
|
'boot' => $hasBoot,
|
|
|
|
|
'booted' => $hasBooted,
|
|
|
|
|
'unboot' => $hasUnboot,
|
|
|
|
|
]),
|
|
|
|
|
'methods' => $methods,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Scan and introspect all available controllers.
|
|
|
|
|
*/
|
|
|
|
|
private static function introspectAllControllers(): array
|
|
|
|
|
{
|
|
|
|
|
// Ensure controllers are scanned
|
|
|
|
|
ControllerResolver::scanControllers();
|
|
|
|
|
|
|
|
|
|
$result = [];
|
|
|
|
|
$seen = [];
|
|
|
|
|
|
|
|
|
|
// Scan app controllers directory
|
|
|
|
|
$appPath = function_exists('app_path')
|
|
|
|
|
? app_path('Websocket/Controllers')
|
|
|
|
|
: null;
|
|
|
|
|
|
|
|
|
|
if ($appPath && is_dir($appPath)) {
|
|
|
|
|
self::scanControllersInPath($appPath, '\\App\\Websocket\\Controllers\\', $result, $seen);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Scan vendor controllers
|
|
|
|
|
$vendorPath = __DIR__ . '/Controllers';
|
|
|
|
|
if (is_dir($vendorPath)) {
|
|
|
|
|
self::scanControllersInPath($vendorPath, '\\BlaxSoftware\\LaravelWebSockets\\Websocket\\Controllers\\', $result, $seen);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [
|
|
|
|
|
'controllers' => $result,
|
|
|
|
|
'total' => count($result),
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Recursively scan a directory for controllers and introspect them.
|
|
|
|
|
*/
|
|
|
|
|
private static function scanControllersInPath(
|
|
|
|
|
string $path,
|
|
|
|
|
string $namespace,
|
|
|
|
|
array &$result,
|
|
|
|
|
array &$seen,
|
|
|
|
|
string $subNamespace = ''
|
|
|
|
|
): void {
|
|
|
|
|
$iterator = new \DirectoryIterator($path);
|
|
|
|
|
|
|
|
|
|
foreach ($iterator as $item) {
|
|
|
|
|
if ($item->isDot()) continue;
|
|
|
|
|
|
|
|
|
|
if ($item->isDir()) {
|
|
|
|
|
self::scanControllersInPath(
|
|
|
|
|
$item->getPathname(),
|
|
|
|
|
$namespace,
|
|
|
|
|
$result,
|
|
|
|
|
$seen,
|
|
|
|
|
$subNamespace . $item->getFilename() . '\\'
|
|
|
|
|
);
|
|
|
|
|
} elseif ($item->isFile() && $item->getExtension() === 'php') {
|
|
|
|
|
$className = $item->getBasename('.php');
|
|
|
|
|
if (! str_ends_with($className, 'Controller')) continue;
|
|
|
|
|
|
|
|
|
|
$fullClass = $namespace . $subNamespace . $className;
|
|
|
|
|
if (isset($seen[$fullClass])) continue;
|
|
|
|
|
$seen[$fullClass] = true;
|
|
|
|
|
|
2026-04-16 07:24:11 +00:00
|
|
|
try {
|
|
|
|
|
if (! class_exists($fullClass, true)) continue;
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
// Class redeclaration or autoload error (e.g. namespace mismatch) — skip
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-04-16 07:02:25 +00:00
|
|
|
if (! is_subclass_of($fullClass, self::class)) continue;
|
|
|
|
|
|
|
|
|
|
// Derive event prefix from class name
|
|
|
|
|
$shortName = str_replace('Controller', '', $className);
|
|
|
|
|
$prefix = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $shortName));
|
|
|
|
|
|
|
|
|
|
$result[] = self::introspectController($fullClass, $prefix);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-05 21:08:47 +00:00
|
|
|
private static function send_error(
|
|
|
|
|
ConnectionInterface $connection,
|
|
|
|
|
array $message,
|
|
|
|
|
string $reason,
|
|
|
|
|
bool $reported = false
|
|
|
|
|
) {
|
|
|
|
|
$connection->send(json_encode([
|
|
|
|
|
'event' => ($message['event'] ?? 'unknown') . ':error',
|
|
|
|
|
'data' => [
|
|
|
|
|
'message' => $reason,
|
|
|
|
|
'meta' => [
|
|
|
|
|
'reported' => $reported,
|
|
|
|
|
],
|
|
|
|
|
],
|
|
|
|
|
'channel' => $message['channel'] ?? null,
|
|
|
|
|
]));
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-16 07:54:02 +00:00
|
|
|
protected static function get_uniquifyer($event)
|
|
|
|
|
{
|
|
|
|
|
preg_match('/[\[].*[\]]/', $event, $matches);
|
|
|
|
|
if (count($matches) === 1) {
|
|
|
|
|
$uniqiueifier = $matches[0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $uniqiueifier ?? null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected static function without_uniquifyer($event)
|
|
|
|
|
{
|
|
|
|
|
return preg_replace('/[\[].*[\]]/', '', $event);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static function get_event($message)
|
|
|
|
|
{
|
2026-04-02 10:44:16 +00:00
|
|
|
// Split on '.' delimiter to get [controller, method, ...]
|
|
|
|
|
// e.g. "admin.dashboard[abc]" → ["admin", "dashboard[abc]"]
|
|
|
|
|
return explode('.', $message['event']);
|
2025-01-16 07:54:02 +00:00
|
|
|
}
|
|
|
|
|
}
|