Passed
Push — main ( a57e19...f52e71 )
by Vedrana
28:10
created

LibraryControllerJson::apiShowBookIsbn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 5
c 1
b 0
f 1
nc 2
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
3
namespace App\Controller;
4
5
use App\Repository\LibraryRepository;
6
use Symfony\Component\HttpFoundation\JsonResponse;
7
use Symfony\Component\Routing\Annotation\Route;
8
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
9
10
/**
11
 * Controller that handles Library JSON API routes.
12
 */
13
class LibraryControllerJson extends AbstractController
14
{
15
    /**
16
    * API library books returns all books in the library.
17
    *
18
    * @param LibraryRepository $libraryRepository to fetch book data.
19
    * @return JsonResponse The list of books in JSON format.
20
    */
21 1
    #[Route("/api/library/books", name: "api_library_books")]
22
    public function apiShowLibrary(LibraryRepository $libraryRepository): JsonResponse
23
    {
24 1
        $books = $libraryRepository->findAll();
25 1
        return $this->createPrettyJsonResponse($books);
26
    }
27
28
    /**
29
     * API library book returns a single book by its ISBN.
30
     *
31
     * @param LibraryRepository $libraryRepository to fetch book data.
32
     * @return JsonResponse
33
     */
34 2
    #[Route("/api/library/book/{isbn}", name: "api_library_isbn")]
35
    public function apiShowBookIsbn(LibraryRepository $libraryRepository, string $isbn): JsonResponse
36
    {
37 2
        $book = $libraryRepository->findOneBy(['isbn' => $isbn]);
38
39 2
        if (!$book) {
40 1
            throw $this->createNotFoundException("No book found with ISBN: $isbn");
41
        }
42 1
        return $this->createPrettyJsonResponse($book);
43
    }
44
45
    /**
46
     * Helper method to create a JSON response with pretty print formatting.
47
     *
48
     * @param mixed $data
49
     * @return JsonResponse The formatted JSON response.
50
     */
51 2
    private function createPrettyJsonResponse(mixed $data): JsonResponse
52
    {
53 2
        $response = $this->json($data);
54 2
        $response->setEncodingOptions(
55 2
            $response->getEncodingOptions() | JSON_PRETTY_PRINT
56 2
        );
57 2
        return $response;
58
    }
59
}
60