Passed
Branch main (02626f)
by Vedrana
05:25
created

LibraryControllerJson   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 13
c 1
b 0
f 1
dl 0
loc 45
ccs 0
cts 14
cp 0
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A apiShowBookIsbn() 0 9 2
A apiShowLibrary() 0 5 1
A createPrettyJsonResponse() 0 7 1
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
    #[Route("/api/library/books", name: "api_library_books")]
22
    public function apiShowLibrary(LibraryRepository $libraryRepository): JsonResponse
23
    {
24
        $books = $libraryRepository->findAll();
25
        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
    #[Route("/api/library/book/{isbn}", name: "api_library_isbn")]
35
    public function apiShowBookIsbn(LibraryRepository $libraryRepository, string $isbn): JsonResponse
36
    {
37
        $book = $libraryRepository->findOneBy(['isbn' => $isbn]);
38
39
        if (!$book) {
40
            throw $this->createNotFoundException("No book found with ISBN: $isbn");
41
        }
42
        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
    private function createPrettyJsonResponse(mixed $data): JsonResponse
52
    {
53
        $response = $this->json($data);
54
        $response->setEncodingOptions(
55
            $response->getEncodingOptions() | JSON_PRETTY_PRINT
56
        );
57
        return $response;
58
    }
59
}
60