Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
CreateBookController
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
2 / 2
3
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
 index
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
2
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\Library\Application\Api;
11
12use AppDemo\Library\Application\Command\CreateBookCommand;
13use Exception;
14use Phexium\Application\AbstractApiController;
15use Phexium\Application\ControllerInterface;
16use Phexium\Plugin\CommandBus\Port\CommandBusInterface;
17use Phexium\Plugin\IdGenerator\Port\IdGeneratorInterface;
18use Phexium\Presentation\ResponseBuilderInterface;
19use Psr\Http\Message\ResponseInterface;
20use Psr\Http\Message\ServerRequestInterface;
21
22final readonly class CreateBookController extends AbstractApiController implements ControllerInterface
23{
24    public function __construct(
25        private CommandBusInterface $commandBus,
26        protected ResponseBuilderInterface $responseBuilder,
27        private IdGeneratorInterface $idGenerator,
28    ) {}
29
30    public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
31    {
32        $data = (array) $request->getParsedBody();
33
34        $formValues = [
35            'title' => $data['title'] ?? '',
36            'author' => $data['author'] ?? '',
37            'isbn' => $data['isbn'] ?? '',
38        ];
39
40        try {
41            $bookId = $this->idGenerator->generate();
42
43            $command = new CreateBookCommand(
44                $bookId,
45                $formValues['title'],
46                $formValues['author'],
47                $formValues['isbn']
48            );
49
50            $this->commandBus->dispatch($command);
51
52            return $this->jsonCreated($response);
53        } catch (Exception $exception) {
54            return $this->jsonError($response, 422, $exception->getMessage());
55        }
56    }
57}