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

LibraryControllerJson::apiShowLibrary()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 3
cp 0
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
    #[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