hanze/memory

memory-backend/src/Controller/GameController.php in main
Repositories | Summary | Log | Files

GameController.php (1863B) download


 1<?php
 2
 3namespace App\Controller;
 4
 5use App\Entity\Player;
 6use App\Entity\Game;
 7
 8use Doctrine\Persistence\ManagerRegistry;
 9use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
10use Symfony\Component\HttpFoundation\Request;
11use Symfony\Component\HttpFoundation\Response;
12use Symfony\Component\Routing\Annotation\Route;
13use Symfony\Component\HttpFoundation\JsonResponse;
14use Symfony\Component\Validator\Constraints\Json;
15use Twig\Error\Error;
16
17#[Route("/game")]
18class 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}