memory

Play Memory
Log | Files | Refs

GameController.php (1863B)


      1 <?php
      2 
      3 namespace App\Controller;
      4 
      5 use App\Entity\Player;
      6 use App\Entity\Game;
      7 
      8 use Doctrine\Persistence\ManagerRegistry;
      9 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
     10 use Symfony\Component\HttpFoundation\Request;
     11 use Symfony\Component\HttpFoundation\Response;
     12 use Symfony\Component\Routing\Annotation\Route;
     13 use Symfony\Component\HttpFoundation\JsonResponse;
     14 use Symfony\Component\Validator\Constraints\Json;
     15 use Twig\Error\Error;
     16 
     17 #[Route("/game")]
     18 class GameController extends AbstractController {
     19     #[Route('/')]
     20     public function index():Response {
     21         return new Response("GameController");
     22     }
     23 
     24     #[Route('/all',methods:['GET'])]
     25     public function getAllGames(ManagerRegistry $doctrine):Response {
     26         $em = $doctrine->getManager();
     27         $game_repo = $em->getRepository(Game::class);
     28         return new JsonResponse($game_repo->findAll());
     29     }
     30 
     31     #[Route("/{id}", requirements: ['id' => '\d+'], methods: ['GET'])]
     32     public function getGame($id, ManagerRegistry $doctrine):Response {
     33         $em = $doctrine->getManager();
     34         $game = $em->find(Game::class, $id);
     35         if ($game) return new JsonResponse($game);
     36         else return new Response('', 404);
     37     }
     38 
     39 
     40     #[Route('/save', methods:['POST'])]
     41     public function saveGame(ManagerRegistry $doctrine):Response {
     42         set_error_handler(fn() => throw new \ErrorException());
     43         try {
     44             $params = json_decode(Request::createFromGlobals()->getContent(), true);
     45             $em = $doctrine->getManager();
     46             $player = $em->find(Player::class, $params['id']);
     47 
     48             $player->addGame(new Game($player, $params));
     49             $em->persist($player);
     50             $em->flush();
     51             return new JsonResponse($player);
     52         } catch (\ErrorException $e) {
     53             return new Response('', 400);
     54         }
     55     }
     56 }