SiteRealtimeService.php 1.2 KB

123456789101112131415161718192021222324
  1. <?php
  2. namespace App\Services;
  3. use Carbon\Carbon;
  4. use Illuminate\Support\Facades\DB;
  5. use InvalidArgumentException;
  6. /** Written inside the same transaction as the change; consumed by the member WebSocket worker. */
  7. final class SiteRealtimeService
  8. {
  9. public static function changed(string $module, int $id, string $action, array $boundaries = []): void
  10. {
  11. if (!in_array($module, ['message', 'announcement', 'maintenance'], true) || $id < 1) throw new InvalidArgumentException('Invalid site event');
  12. $now = Carbon::now('Asia/Shanghai')->format('Y-m-d H:i:s');
  13. DB::table('site_realtime_events')->where('module', $module)->where('resource_id', $id)
  14. ->whereNull('dispatched_at')->where('available_at', '>', $now)->delete();
  15. $rows = [['module' => $module, 'resource_id' => $id, 'action' => $action, 'available_at' => $now, 'created_at' => $now]];
  16. foreach ($boundaries as $edge => $at) {
  17. if ($at !== null && $at > $now) $rows[] = ['module' => $module, 'resource_id' => $id, 'action' => $edge, 'available_at' => $at, 'created_at' => $now];
  18. }
  19. DB::table('site_realtime_events')->insert($rows);
  20. }
  21. }