src/Controller/Admin/PresenceController.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Service\PresenceService;
  4. use Psr\Cache\InvalidArgumentException;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\Mercure\HubInterface;
  8. use Symfony\Component\Mercure\Update;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. class PresenceController extends AbstractController
  12. {
  13.     public function __construct(private readonly PresenceService $presenceService)
  14.     {
  15.     }
  16.     /**
  17.      * @Route("/presence", name="api_presence_update", methods={"POST"})
  18.      * @throws InvalidArgumentException
  19.      */
  20.     public function updatePresence(Request $requestHubInterface $hub): JsonResponse
  21.     {
  22.         $data json_decode($request->getContent(), true);
  23.         $userId $data['userId'] ?? null;
  24.         $status $data['status'] ?? null;
  25.         if (!$userId || $status === null) {
  26.             return new JsonResponse(['error' => 'Missing userId or status'], 400);
  27.         }
  28.         if ($status) {
  29.             $this->presenceService->markOnline($userId);
  30.         } else {
  31.             $this->presenceService->markOffline($userId);
  32.         }
  33.         $hub->publish(new Update(
  34.             'presence',
  35.             json_encode(['userId' => $userId'status' => $status])
  36.         ));
  37.         return new JsonResponse([
  38.             'success' => true,
  39.             'userId' => $userId,
  40.             'status' => $status
  41.         ]);
  42.     }
  43.     /**
  44.      * @Route("/presence", name="api_presence_list", methods={"GET"})
  45.      * @throws InvalidArgumentException
  46.      */
  47.     public function listOnlineUsers(): JsonResponse
  48.     {
  49.         $onlineUsers $this->presenceService->getOnlineUsers();
  50.         return new JsonResponse(array_keys($onlineUsers));
  51.     }
  52. }