Passed
Push — main ( f3cfb1...17781b )
by Emil
04:34
created

BookController::createBookPOST()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 1
1
<?php
2
3
namespace App\Controller;
4
5
use App\Entity\Book;
6
use App\Repository\BookRepository;
7
use App\UploadManager;
8
use Doctrine\Persistence\ManagerRegistry;
9
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
10
use Symfony\Component\HttpFoundation\File\UploadedFile;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Routing\Attribute\Route;
14
15
class BookController extends AbstractController
16
{
17
    private const FILE_TYPES_SUPPORTED = ['image/jpeg'];
18
19
    /**
20
     * getInputs.
21
     *
22
     * Returns a array that contains all the user inputs
23
     *
24
     * @return array<mixed>
25
     */
26 1
    private function getInputs(Request $request): array
27
    {
28 1
        $id = htmlspecialchars((string) $request->request->get('id'));
29 1
        $title = htmlspecialchars((string) $request->request->get('title'));
30 1
        $isbn = htmlspecialchars((string) $request->request->get('isbn'));
31 1
        $author = htmlspecialchars((string) $request->request->get('author'));
32
        /** @var UploadedFile|null $file */
33 1
        $file = $request->files->get('img');
34
35 1
        $inputs = [
36 1
            'id' => $id,
37 1
            'title' => $title,
38 1
            'isbn' => $isbn,
39 1
            'author' => $author,
40 1
            'file' => $file,
41 1
        ];
42
43 1
        return $inputs;
44
    }
45
46
    /**
47
     * saveBook.
48
     *
49
     * Saves the book to database
50
     */
51 1
    private function saveBook(Request $request, ManagerRegistry $doctrine): void
52
    {
53
        // Get the inputs
54 1
        $inputs = $this->getInputs($request);
55
        /** @var string $title */
56 1
        $title = $inputs['title'];
57
        /** @var string $isbn */
58 1
        $isbn = $inputs['isbn'];
59
        /** @var string $author */
60 1
        $author = $inputs['author'];
61
        /** @var UploadedFile|null $file */
62 1
        $file = $inputs['file'];
63
64
        // Check if empty title
65 1
        if ('' === $title) {
66 1
            $this->addFlash(
67 1
                'warning',
68 1
                'Could not read the title!'
69 1
            );
70
71 1
            return;
72
        }
73
74 1
        $img = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $img is dead and can be removed.
Loading history...
75
        /** @var string $projectDir */
76 1
        $projectDir = $this->getParameter('kernel.project_dir');
77 1
        $uploadManager = new UploadManager($projectDir);
78
79
        try {
80 1
            $img = $uploadManager->saveUploadedFile($file, self::FILE_TYPES_SUPPORTED);
81
            // After setting $img
82
        } catch (\RuntimeException $e) {
83
            $this->addFlash(
84
                'warning',
85
                $e->getMessage()
86
            );
87
88
            return;
89
        }
90
91 1
        $bookRepository = new BookRepository($doctrine);
92
93 1
        $bookRepository->saveBook($title, $isbn, $author, $img);
94
95 1
        $this->addFlash(
96 1
            'notice',
97 1
            'You have gone created a book!'
98 1
        );
99
    }
100
101
    /**
102
     * updateBook.
103
     *
104
     * Update the book in database
105
     */
106 1
    private function updateBook(Request $request, ManagerRegistry $doctrine): void
107
    {
108 1
        $inputs = $this->getInputs($request);
109
        /** @var string $id */
110 1
        $id = $inputs['id'];
111
        /** @var string $title */
112 1
        $title = $inputs['title'];
113
        /** @var string $isbn */
114 1
        $isbn = $inputs['isbn'];
115
        /** @var string $author */
116 1
        $author = $inputs['author'];
117
        /** @var UploadedFile|null $file */
118 1
        $file = $inputs['file'];
119
120
        // Check if empty id
121 1
        if ('' === $id) {
122
            $this->addFlash(
123
                'warning',
124
                'Could not read the id!'
125
            );
126
127
            return;
128
        }
129
130
        // Retrieve the existing book entity
131 1
        $bookRepository = new BookRepository($doctrine);
132
133 1
        $book = $bookRepository->find($id);
134
135
        // Check if book exists
136 1
        if (!$book) {
137 1
            $this->addFlash(
138 1
                'warning',
139 1
                'Book not found with ID '.$id
140 1
            );
141
142 1
            return;
143
        }
144
145
        // Check if empty title
146 1
        if ('' === $title) {
147 1
            $this->addFlash(
148 1
                'warning',
149 1
                'Could not read the title!'
150 1
            );
151
152 1
            return;
153
        }
154
155
        // Save new image
156 1
        $img = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $img is dead and can be removed.
Loading history...
157
        /** @var string $projectDir */
158 1
        $projectDir = $this->getParameter('kernel.project_dir');
159 1
        $uploadManager = new UploadManager($projectDir);
160
161
        try {
162 1
            $img = $uploadManager->saveUploadedFile($file, self::FILE_TYPES_SUPPORTED);
163
            // After setting $img
164
        } catch (\RuntimeException $e) {
165
            $this->addFlash(
166
                'warning',
167
                $e->getMessage()
168
            );
169
170
            return;
171
        }
172
173
        // If you have new image
174 1
        if (null !== $img) {
175
            // If old image existed remove it
176
            $oldImage = $book->getImg();
177
            if (null !== $oldImage) {
178
                if (!$uploadManager->deleteUploadedFile($oldImage)) {
179
                    $this->addFlash(
180
                        'notice',
181
                        'Could not remove old img!'
182
                    );
183
                }
184
            }
185
        }
186
187
        // Update the book
188 1
        $bookRepository->updateBook((int) $id, $title, $isbn, $author, $img);
189
190 1
        $this->addFlash(
191 1
            'notice',
192 1
            'The book has been updated successfully!'
193 1
        );
194
    }
195
196
    /**
197
     * deleteBook.
198
     *
199
     * Update the book in database
200
     */
201 1
    private function deleteBook(int $id, ManagerRegistry $doctrine): void
202
    {
203
        // Retrieve the existing book entity
204 1
        $bookRepository = new BookRepository($doctrine);
205
206 1
        $book = $bookRepository->find($id);
207
208
        // Check if book don't exists
209 1
        if (!$book) {
210 1
            $this->addFlash(
211 1
                'warning',
212 1
                'Book not found with ID '.$id
213 1
            );
214
215 1
            return;
216
        }
217
218
        // Delete image
219 1
        $img = $book->getImg();
220
        /** @var string $projectDir */
221 1
        $projectDir = $this->getParameter('kernel.project_dir');
222 1
        $uploadManager = new UploadManager($projectDir);
223
224 1
        if (null !== $img) {
225
            if (!$uploadManager->deleteUploadedFile($img)) {
226
                $this->addFlash(
227
                    'notice',
228
                    'Could not remove img: '.$img
229
                );
230
            }
231
        }
232
233 1
        $bookRepository->deleteBook($id);
234
235 1
        $this->addFlash(
236 1
            'notice',
237 1
            'The book has been deleted!'
238 1
        );
239
    }
240
241 1
    #[Route('/library', name: 'library')]
242
    public function library(): Response
243
    {
244 1
        return $this->render('book/index.html.twig');
245
    }
246
247 1
    #[Route('/book/create', name: 'book_create_get', methods: 'GET')]
248
    public function createBookGET(): Response
249
    {
250 1
        return $this->render('book/create.html.twig');
251
    }
252
253 1
    #[Route('/book/create', name: 'book_create_post', methods: 'POST')]
254
    public function createBookPOST(
255
        Request $request,
256
        ManagerRegistry $doctrine,
257
    ): Response {
258
        // Save book to database
259 1
        $this->saveBook($request, $doctrine);
260
261 1
        return $this->redirectToRoute('book_create_get');
262
    }
263
264 1
    #[Route('/book/show', name: 'book_show_all')]
265
    public function showAllBooks(
266
        ManagerRegistry $doctrine,
267
    ): Response {
268 1
        $bookRepository = new BookRepository($doctrine);
269
270 1
        $data = $bookRepository->readAllBooks();
271
272 1
        return $this->render('book/show.html.twig', $data);
273
    }
274
275 1
    #[Route('/book/show/{id<\d+>}', name: 'book_show_one')]
276
    public function showOneBook(
277
        int $id,
278
        ManagerRegistry $doctrine,
279
    ): Response {
280 1
        $bookRepository = new BookRepository($doctrine);
281
282 1
        $data = $bookRepository->readOneBook($id);
283
284 1
        return $this->render('book/show_one.html.twig', $data);
285
    }
286
287 1
    #[Route('/book/show/update', name: 'book_show_all_update')]
288
    public function showAllBooksUpdate(
289
        ManagerRegistry $doctrine,
290
    ): Response {
291 1
        $bookRepository = new BookRepository($doctrine);
292
293 1
        $data = $bookRepository->readAllBooks();
294
295 1
        return $this->render('book/show_update.html.twig', $data);
296
    }
297
298 1
    #[Route('/book/update/{id<\d+>}', name: 'book_update_get', methods: ['GET'])]
299
    public function showAllBooksUpdateGET(
300
        int $id,
301
        ManagerRegistry $doctrine,
302
    ): Response {
303 1
        $bookRepository = new BookRepository($doctrine);
304
305 1
        $data = $bookRepository->readOneBook($id);
306
307 1
        return $this->render('book/update.html.twig', $data);
308
    }
309
310 1
    #[Route('/book/update', name: 'book_update_post', methods: ['POST'])]
311
    public function showAllBooksUpdatePOST(
312
        Request $request,
313
        ManagerRegistry $doctrine,
314
    ): Response {
315 1
        $inputs = $this->getInputs($request);
316
317
        // Update book to database
318 1
        $this->updateBook($request, $doctrine);
319
320 1
        return $this->redirectToRoute('book_update_get', ['id' => $inputs['id']]);
321
    }
322
323 1
    #[Route('/book/show/delete', name: 'book_show_all_delete_get', methods: ['GET'])]
324
    public function showAllBooksDeleteGET(
325
        ManagerRegistry $doctrine,
326
    ): Response {
327 1
        $bookRepository = new BookRepository($doctrine);
328
329 1
        $data = $bookRepository->readAllBooks();
330
331 1
        return $this->render('book/show_delete.html.twig', $data);
332
    }
333
334 1
    #[Route('/book/show/delete/{id<\d+>}', name: 'book_delete_post', methods: ['POST'])]
335
    public function showAllBooksDeletePOST(
336
        int $id,
337
        ManagerRegistry $doctrine,
338
    ): Response {
339
        // Delete book to database
340 1
        $this->deleteBook($id, $doctrine);
341
342 1
        return $this->redirectToRoute('book_show_all_delete_get');
343
    }
344
}
345