2026-10-28 18:17:34 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Websocket;
|
|
|
|
|
|
|
|
|
|
use App\Game\GameRuleViolation;
|
2026-10-28 18:24:09 +00:00
|
|
|
use BlaxSoftware\LaravelWebSockets\Services\WebsocketService;
|
2026-10-28 18:17:34 +00:00
|
|
|
use BlaxSoftware\LaravelWebSockets\Websocket\Controller;
|
|
|
|
|
use Closure;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Base for the game's WS controllers: authed only, and a refused intent answers
|
|
|
|
|
* `<event>:error` with `{message, code}` so the client can translate the code.
|
|
|
|
|
* Lives outside Controllers/ so the resolver never maps an event to it.
|
|
|
|
|
*/
|
|
|
|
|
abstract class GameController extends Controller
|
|
|
|
|
{
|
|
|
|
|
public $need_auth = true;
|
|
|
|
|
|
2026-10-28 18:24:09 +00:00
|
|
|
/**
|
|
|
|
|
* The client sends its bearer token as `authtoken` with every message, which the
|
|
|
|
|
* package resolves through Sanctum for that message only. Remember the socket's
|
|
|
|
|
* user, so the server authenticates its next messages itself (`socket_<id>`) and
|
|
|
|
|
* the game:events worker can find the owner's sockets for pushes.
|
|
|
|
|
*/
|
|
|
|
|
public function booted()
|
|
|
|
|
{
|
|
|
|
|
$user = auth()->user();
|
|
|
|
|
$socketId = $this->connection->socketId ?? null;
|
|
|
|
|
if (! $user || ! $socketId) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
cache()->put("socket_$socketId", ['id' => $user->id, 'type' => $user::class], now()->addDay());
|
|
|
|
|
if ((WebsocketService::getAuthedUsers()[$socketId] ?? null) !== $user->id) {
|
|
|
|
|
WebsocketService::setUserAuthed($socketId, $user);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-28 18:17:34 +00:00
|
|
|
protected function play(Closure $intent): mixed
|
|
|
|
|
{
|
|
|
|
|
try {
|
|
|
|
|
return $intent();
|
|
|
|
|
} catch (GameRuleViolation $e) {
|
|
|
|
|
return $this->error(['message' => $e->getMessage(), 'code' => $e->reason]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|