<?php
namespace App\Controller\Admin;
use App\Service\PresenceService;
use Psr\Cache\InvalidArgumentException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class PresenceController extends AbstractController
{
public function __construct(private readonly PresenceService $presenceService)
{
}
/**
* @Route("/presence", name="api_presence_update", methods={"POST"})
* @throws InvalidArgumentException
*/
public function updatePresence(Request $request, HubInterface $hub): JsonResponse
{
$data = json_decode($request->getContent(), true);
$userId = $data['userId'] ?? null;
$status = $data['status'] ?? null;
if (!$userId || $status === null) {
return new JsonResponse(['error' => 'Missing userId or status'], 400);
}
if ($status) {
$this->presenceService->markOnline($userId);
} else {
$this->presenceService->markOffline($userId);
}
$hub->publish(new Update(
'presence',
json_encode(['userId' => $userId, 'status' => $status])
));
return new JsonResponse([
'success' => true,
'userId' => $userId,
'status' => $status
]);
}
/**
* @Route("/presence", name="api_presence_list", methods={"GET"})
* @throws InvalidArgumentException
*/
public function listOnlineUsers(): JsonResponse
{
$onlineUsers = $this->presenceService->getOnlineUsers();
return new JsonResponse(array_keys($onlineUsers));
}
}