game-village-politics-backend/app/Engine/Push.php

75 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace App\Engine;
use App\Models\Village;
use BlaxSoftware\LaravelWebSockets\Services\WebsocketService;
use Throwable;
/**
* Tells the owners' open sockets that a village changed, so their clients refetch.
* Game code queues villages while it holds locks; the caller flushes after the commit.
*/
final class Push
{
/** @var array<int, true> */
private static array $queued = [];
/** @var list<array{user: int, payload: array<string, mixed>}> */
private static array $lost = [];
/** The old owner of a taken village hears of it, to leave its screens and read the report. */
public static function lost(int $userId, array $payload): void
{
self::$lost[] = ['user' => $userId, 'payload' => $payload];
}
public static function queue(int ...$villageIds): void
{
foreach ($villageIds as $id) {
self::$queued[$id] = true;
}
}
public static function flush(): void
{
$ids = array_keys(self::$queued);
$lost = self::$lost;
self::$queued = [];
self::$lost = [];
self::villages($ids);
if ($lost && ws_available()) {
foreach ($lost as $l) {
try {
$sockets = WebsocketService::getUserSocketIds($l['user']);
if ($sockets) {
ws_whisper('village:lost', $l['payload'], $sockets);
}
} catch (Throwable $e) {
report($e);
}
}
}
}
/** @param list<int> $villageIds */
public static function villages(array $villageIds): void
{
if (! $villageIds || ! ws_available()) {
return;
}
foreach (Village::with('player')->whereIn('id', $villageIds)->get() as $village) {
$userId = $village->player?->user_id;
try {
$sockets = $userId ? WebsocketService::getUserSocketIds($userId) : [];
if ($sockets) {
ws_whisper('village:updated', ['village_id' => $village->id], $sockets);
}
} catch (Throwable $e) {
// A push is a hint to refetch; the game state is already saved.
report($e);
}
}
}
}