DefaultController.php (2081B) download
1<?php
2
3namespace App\Controller;
4
5use App\Entity\Player;
6use Doctrine\Persistence\ManagerRegistry;
7use Psr\Log\LoggerInterface;
8use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
9
10use Symfony\Component\HttpFoundation\Request;
11use Symfony\Component\HttpFoundation\Response;
12use Symfony\Component\Routing\Annotation\Route;
13use Symfony\Component\HttpFoundation\JsonResponse;
14
15class DefaultController extends AbstractController {
16 #[Route('/', methods:['GET'])]
17 public function index(LoggerInterface $logger):Response {
18// $logger->info("Hallo allemaal");dd
19 return new Response('DefaultController');
20 }
21
22 #[Route('/frontend', methods:['GET'])]
23 public function demo():Response {
24 $rv['message'] = 'Welkom bij de memory backend api.';
25 $rv['date'] = date("F j, Y, g:i a");
26 return new JsonResponse($rv);
27 }
28
29 #[Route('/api/login_check', methods:['POST'])]
30 public function login():Response {
31 return new Response('');
32 }
33
34 #[Route('/scores', methods: ['GET'])]
35 public function scores(ManagerRegistry $doctrine)
36 {
37 $em = $doctrine->getManager();
38 $scores = $em->createQuery("select p.username, avg(g.score) as score from App\Entity\Player p
39 join p.games g group by p.username")->getArrayResult();
40 return new JsonResponse($scores);
41 }
42
43 #[Route('/register', methods: ['POST'])]
44 public function register(ManagerRegistry $doctrine): Response {
45 set_error_handler(fn() => throw new \ErrorException());
46
47 try {
48 $params = json_decode(Request::createFromGlobals()->getContent(), true);
49 $pw = password_hash($params['password'], PASSWORD_DEFAULT);
50 $player = new Player($params['username'], $params['email'], $pw);
51 $em = $doctrine->getManager();
52 $em->persist($player);
53 $em->flush();
54 return new Response("", 201, ["Location" => "/player/$player->id"]);
55 } catch (\ErrorException $e) {
56 return new Response("",400);
57 }
58 }
59}