Jacek Kowalski
4 hours ago 6b9278a5d57091fce636dbb640b380cfb990db6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
declare(strict_types=1);
 
namespace App\Controller;
 
use App\Entity\Book;
use App\Entity\Label;
use App\Form\AddLabelType;
use App\Repository\BookRepository;
use App\Repository\LabelRepository;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Requirement\Requirement;
 
class LabelController extends AbstractController {
    #[Route('/book/{id}/labels', name: 'label_add', requirements: ['id' => Requirement::DIGITS], methods: ['POST'])]
    public function add(Request $request, Book $book, EntityManagerInterface $entityManager): Response {
        $form = $this->createForm(AddLabelType::class);
        $form->handleRequest($request);
 
        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            $book->addLabel($data['label'], $data['type']);
            $entityManager->flush();
        } else {
            $this->addFlash('error', 'action_rejected');
        }
 
        return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
    }
 
    #[Route('/label/{id}/remove', name: 'label_remove', requirements: ['id' => Requirement::DIGITS], methods: ['POST'])]
    public function remove(Request $request, Label $label, EntityManagerInterface $entityManager): Response {
        $book = $label->getBook();
 
        if ($this->isCsrfTokenValid('remove-label' . $label->getId(), $request->getPayload()->getString('_token'))) {
            $book->removeLabel($label);
            $entityManager->flush();
        } else {
            $this->addFlash('error', 'action_rejected');
        }
 
        return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
    }
}