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
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types=1);
 
namespace App\Controller;
 
use App\Entity\Book;
use App\Form\CoverType;
use App\Service\CoverProcessingException;
use App\Service\CoverStorage;
use App\Service\Library;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Requirement\Requirement;
 
class CoverController extends AbstractController {
    #[Route('/cover/{name}', name: 'cover_original', requirements: ['name' => '[0-9a-f]{32}\.(jpg|png|webp)'], methods: ['GET'])]
    public function original(string $name, CoverStorage $covers): Response {
        $path = $covers->originalPath($name);
 
        if (!is_file($path)) {
            throw $this->createNotFoundException();
        }
 
        $response = new BinaryFileResponse($path);
        $response->headers->set('X-Content-Type-Options', 'nosniff');
 
        return $response;
    }
 
    #[Route('/book/{id}/cover', name: 'cover_upload', requirements: ['id' => Requirement::DIGITS], methods: ['POST'])]
    public function upload(Request $request, Book $book, Library $library): Response {
        $form = $this->createForm(CoverType::class);
        $form->handleRequest($request);
 
        if (!$form->isSubmitted()) {
            $this->addFlash('error', 'cover_too_large');
        } elseif (!$form->isValid()) {
            $this->addFlash('error', $form->getErrors(true)->current()->getMessage());
        } else {
            try {
                $library->changeCover($book, $form->getData()['cover']);
                $this->addFlash('success', 'cover_saved');
            } catch (CoverProcessingException) {
                $this->addFlash('error', 'cover_failed');
            }
        }
 
        return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
    }
 
    #[Route('/book/{id}/cover/remove', name: 'cover_remove', requirements: ['id' => Requirement::DIGITS], methods: ['POST'])]
    public function remove(Request $request, Book $book, Library $library): Response {
        if ($this->isCsrfTokenValid('remove-cover' . $book->getId(), $request->getPayload()->getString('_token'))) {
            $library->changeCover($book, null);
        } else {
            $this->addFlash('error', 'action_rejected');
        }
 
        return $this->redirectToRoute('book_show', ['id' => $book->getId()]);
    }
}