src/Controller/Public/PublicController.php line 80

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Public;
  3. use App\Entity\Person\Person;
  4. use App\Entity\World;
  5. use App\Service\WsServerHttpClient;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. class PublicController extends AbstractController
  13. {
  14.     public function __construct(
  15.         private readonly EntityManagerInterface $entityManager,
  16.         private readonly WsServerHttpClient $httpClient,
  17.     ) {}
  18.     #[Route('/game'name'public_game'methods: ['GET'])]
  19.     public function game(): Response
  20.     {
  21.         return $this->render('public/game.html.twig', [
  22.             'name' => 'Чат',
  23.             'gameServerUrl' => $_ENV['GAME_WSSERVER_URL'],
  24.         ]);
  25.     }
  26.     #[Route('/game/invite/{roomId}'name'public_invite'methods: ['GET'])]
  27.     public function invite(?string $roomId): Response
  28.     {
  29.         try {
  30.             // Делаем запрос к серверу для получения информации о комнатах
  31.             $response $this->httpClient->request('GET''room/get');
  32.             $rooms $response->toArray();
  33.             
  34.             // Ищем комнату по roomId
  35.             $foundRoom null;
  36.             foreach ($rooms as $room) {
  37.                 if ($room['id'] === $roomId) {
  38.                     $foundRoom $room;
  39.                     break;
  40.                 }
  41.             }
  42.             
  43.             if (!$foundRoom) {
  44.                 throw $this->createNotFoundException('Room not found');
  45.             }
  46.             
  47.             // Получаем worldId из найденной комнаты
  48.             $worldId $foundRoom['worldId'] ?? null;
  49.             if (!$worldId) {
  50.                 throw $this->createNotFoundException('World ID not found in room');
  51.             }
  52.             
  53.             // Ищем мир в репозитории
  54.             $worldRepository $this->entityManager->getRepository(World::class);
  55.             $world $worldRepository->find($worldId);
  56.             if (!$world) {
  57.                 throw $this->createNotFoundException('World not found');
  58.             }
  59.             $personRepository $this->entityManager->getRepository(Person::class);
  60.             $persons $personRepository->findBy(['world' => $world]);
  61.             return $this->render('public/invite/king.html.twig', [
  62.                 'roomId' => $roomId,
  63.                 'worldName' => $world->getName(),
  64.                 'worldDescription' => $world->getDescription(),
  65.                 'persons' => $persons,
  66.             ]);
  67.         } catch (\Exception $e) {
  68.             throw $this->createNotFoundException('Room not found: ' $e->getMessage());
  69.         }
  70.     }
  71.     #[Route('/'name'public_index'methods: ['GET'])]
  72.     public function index(): Response
  73.     {
  74.         // Получаем список всех миров из репозитория
  75.         $worldRepository $this->entityManager->getRepository(World::class);
  76.         $worlds $worldRepository->findAll();
  77.         
  78.         // Фильтруем миры, которые публичные
  79.         $availableWorlds array_filter($worlds, function (World $world) {
  80.             return $world->isPublic();
  81.         });
  82.         $availableWorlds array_values($availableWorlds);
  83.         
  84.         return $this->render('public/game_list.html.twig', [
  85.             'worlds' => $availableWorlds,
  86.         ]);
  87.     }
  88.     #[Route('/world/{id}'name'public_world_view'methods: ['GET'])]
  89.     public function viewWorld(string $id): Response
  90.     {
  91.         // Получаем мир из репозитория
  92.         $worldRepository $this->entityManager->getRepository(World::class);
  93.         $world $worldRepository->find($id);
  94.         
  95.         if (!$world) {
  96.             throw $this->createNotFoundException('Мир не найден');
  97.         }
  98.         
  99.         if (!$world->isPublic()) {
  100.             throw $this->createNotFoundException('Мир не доступен');
  101.         }
  102.         
  103.         return $this->render('public/world_view.html.twig', [
  104.             'world' => $world,
  105.         ]);
  106.     }
  107.     #[Route('/game/create/{worldId}'name'public_create_room'methods: ['POST'])]
  108.     public function createRoom(string $worldId): Response
  109.     {
  110.         try {
  111.             // Проверяем существование мира
  112.             $worldRepository $this->entityManager->getRepository(World::class);
  113.             $world $worldRepository->find($worldId);
  114.             
  115.             if (!$world) {
  116.                 throw $this->createNotFoundException('World not found');
  117.             }
  118.             // Проверяем, что мир готов к публикации
  119.             if (!$world->isReadyToPub()) {
  120.                 throw $this->createNotFoundException('World is not ready to publish');
  121.             }
  122.             // Создаем комнату через WebSocket сервер
  123.             $response $this->httpClient->request('POST''room/create', [
  124.                 'json' => [
  125.                     'worldId' => $worldId
  126.                 ]
  127.             ]);
  128.             
  129.             $roomData $response->toArray();
  130.             $roomId $roomData['room_id'] ?? null;
  131.             
  132.             if (!$roomId) {
  133.                 throw new \Exception('Request failed');
  134.             }
  135.             // Перенаправляем на страницу приглашения
  136.             return $this->redirectToRoute('public_invite', ['roomId' => $roomId]);
  137.         } catch (\Exception $e) {
  138.             throw $this->createNotFoundException('Failed to create room: ' $e->getMessage());
  139.         }
  140.     }
  141.     
  142.     #[Route('/game/register/{roomId}'name'public_game_register'methods: ['POST'])]
  143.     public function register(string $roomIdRequest $request): Response
  144.     {
  145.         try {
  146.             // Получаем данные из запроса
  147.             $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  148.             
  149.             // Формируем данные для отправки на сервер регистрации
  150.             $registerData = [
  151.                 'name' => $data['name'] ?? '',
  152.                 'person_id' => $data['person_id'] ?? '',
  153.                 'room_id' => $roomId,
  154.             ];
  155.             
  156.             // Отправляем запрос на существующий маршрут /register через WebSocket клиент
  157.             $response $this->httpClient->request('POST''register', [
  158.                 'json' => $registerData
  159.             ]);
  160.             
  161.             // Возвращаем ответ от сервера
  162.             $responseData $response->toArray();
  163.             
  164.             // Создаем JSON ответ с cookie в теле
  165.             return new JsonResponse($responseData);
  166.             
  167.         } catch (\Exception $e) {
  168.             return new JsonResponse(['error' => 'Registration failed: ' $e->getMessage()], 500);
  169.         }
  170.     }
  171. }