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
50
51
52
53
54
<?php
declare(strict_types=1);
 
namespace App\Controller;
 
use App\Entity\Book;
use App\Form\BorrowType;
use App\Repository\BorrowRepository;
use App\Service\Library;
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 BorrowController extends AbstractController {
    #[Route('/borrowed', name: 'borrow_list', methods: ['GET'])]
    public function list(Request $request, BorrowRepository $borrows, PaginatorInterface $paginator): Response {
        return $this->render('borrow/list.html.twig', [
            'pagination' => $paginator->paginate(
                $borrows->createListQueryBuilder(),
                max(1, $request->query->getInt('page', 1)),
            ),
        ]);
    }
 
    #[Route('/book/{id}/lend', name: 'book_lend', requirements: ['id' => Requirement::DIGITS], methods: ['POST'])]
    public function lend(Request $request, Book $book, Library $library): Response {
        $form = $this->createForm(BorrowType::class);
        $form->handleRequest($request);
 
        if (!$book->isBorrowed() && $form->isSubmitted() && $form->isValid()) {
            $library->lend($book, $form->getData()['who']);
            $this->addFlash('success', 'borrow_lent');
        } else {
            $this->addFlash('error', 'action_rejected');
        }
 
        return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
    }
 
    #[Route('/book/{id}/return', name: 'book_return', requirements: ['id' => Requirement::DIGITS], methods: ['POST'])]
    public function return(Request $request, Book $book, Library $library): Response {
        if ($book->isBorrowed() && $this->isCsrfTokenValid('return' . $book->getId(), $request->getPayload()->getString('_token'))) {
            $library->giveBack($book);
            $this->addFlash('success', 'borrow_returned');
        } else {
            $this->addFlash('error', 'action_rejected');
        }
 
        return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
    }
}