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

52 lines
1.4 KiB
PHP

<?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 = [];
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);
self::$queued = [];
self::villages($ids);
}
/** @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);
}
}
}
}