Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
BorrowBookController
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
4 / 4
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 showBorrowForm
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 borrowBook
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
3
 renderFormResponse
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3// ╔════════════════════════════════════════════════════════════╗
4// ║ MIT Licence (#Expat) - https://opensource.org/licenses/MIT ║
5// ║ Copyright 2026 Frederic Poeydomenge <dyno@phexium.com>     ║
6// ╚════════════════════════════════════════════════════════════╝
7
8declare(strict_types=1);
9
10namespace AppDemo\Loan\Application\Http;
11
12use AppDemo\Loan\Application\Command\BorrowBookCommand;
13use AppDemo\Loan\Application\Query\BorrowBookQuery;
14use AppDemo\Loan\Domain\Exception\BookNotAvailableException;
15use AppDemo\Loan\Domain\LoanPeriod;
16use AppDemo\Loan\Presentation\BorrowBookHtmlPresenter;
17use AppDemo\Loan\Presentation\Request\BorrowBookRequest;
18use AppDemo\Shared\Application\AbstractHttpController;
19use AppDemo\Shared\Domain\Interface\SessionServiceInterface;
20use InvalidArgumentException;
21use Phexium\Application\ControllerInterface;
22use Phexium\Plugin\CommandBus\Port\CommandBusInterface;
23use Phexium\Plugin\IdGenerator\Port\IdGeneratorInterface;
24use Phexium\Plugin\Logger\Port\LoggerInterface;
25use Phexium\Plugin\QueryBus\Port\QueryBusInterface;
26use Phexium\Presentation\ResponseBuilderInterface;
27use Psr\Http\Message\ResponseInterface;
28use Psr\Http\Message\ServerRequestInterface;
29use Twig\Environment;
30
31final readonly class BorrowBookController extends AbstractHttpController implements ControllerInterface
32{
33    public function __construct(
34        private CommandBusInterface $commandBus,
35        private QueryBusInterface $queryBus,
36        private SessionServiceInterface $sessionService,
37        private BorrowBookHtmlPresenter $presenter,
38        private Environment $twig,
39        private ResponseBuilderInterface $responseBuilder,
40        private IdGeneratorInterface $idGenerator,
41        private LoggerInterface $logger,
42    ) {}
43
44    public function showBorrowForm(
45        ServerRequestInterface $request, // NOSONAR - Slim Framework PSR-15 contract
46        ResponseInterface $response
47    ): ResponseInterface {
48        return $this->renderFormResponse($response);
49    }
50
51    public function borrowBook(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
52    {
53        $this->logger->info('BorrowBookController: Processing request');
54
55        $requestDto = BorrowBookRequest::fromHttpRequest($request);
56        $errors = $requestDto->validate();
57
58        if ($errors === []) {
59            try {
60                $loanId = $this->idGenerator->generate();
61                $userId = $this->getUserId($request);
62                $bookId = $this->idGenerator->from($requestDto->bookId);
63                $loanPeriod = LoanPeriod::fromInt((int) $requestDto->loanPeriod);
64
65                $command = new BorrowBookCommand($loanId, $userId, $bookId, $loanPeriod);
66
67                $this->commandBus->dispatch($command);
68
69                $this->sessionService->addFlashMessage('success', 'Book borrowed successfully!');
70
71                return $this->responseBuilder
72                    ->withResponse($response)
73                    ->withStatus(302)
74                    ->withHeader('Location', '/loans/my')
75                    ->build()
76                ;
77            } catch (BookNotAvailableException|InvalidArgumentException $e) {
78                $errors['book_id'] = $e->getMessage();
79            }
80        }
81
82        $this->logger->warning('BorrowBookController: Validation errors', ['errors' => $errors]);
83
84        return $this->renderFormResponse($response, $requestDto->toArray(), $errors);
85    }
86
87    private function renderFormResponse(
88        ResponseInterface $response,
89        array $formValues = [],
90        array $errors = []
91    ): ResponseInterface {
92        $query = new BorrowBookQuery($formValues, $errors);
93        $queryResponse = $this->queryBus->dispatch($query);
94
95        $viewModel = $this->presenter->present($queryResponse)->getViewModel();
96        $html = $this->twig->render('BorrowBook.html.twig', (array) $viewModel);
97
98        return $this->responseBuilder
99            ->withResponse($response)
100            ->withStatus(200)
101            ->withHtml($html)
102            ->build()
103        ;
104    }
105}