<?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()]);
|
}
|
}
|