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

LibraryControllerJson   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A apiShowLibrary() 0 5 1
A apiShowBookIsbn() 0 9 2
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 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