Lines 100.00% 14 / 14
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AddActionController 100.00% 14 / 14 100.00% 2 / 2 3 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 __invoke 100.00% 13 / 13 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Districts\Editor\UI\Controller;
6
7use Districts\Editor\Application\DistrictService;
8use Districts\Editor\Application\Exception\ValidationException;
9use Districts\Editor\UI\Factory\AddDistrictCommandFactory;
10use Districts\Editor\UI\Session;
11use Fig\Http\Message\StatusCodeInterface as StatusCode;
12use Psr\Http\Message\ResponseFactoryInterface as ResponseFactory;
13use Psr\Http\Message\ResponseInterface as Response;
14use Psr\Http\Message\ServerRequestInterface as Request;
15use Slim\Interfaces\RouteParserInterface;
16
17final readonly class AddActionController
18{
19    public function __construct(
20        private DistrictService $districtService,
21        private AddDistrictCommandFactory $commandFactory,
22        private Session $session,
23        private RouteParserInterface $routeParser,
24        private ResponseFactory $responseFactory,
25    ) {
26    }
27
28    /**
29     * @param array<string, string> $args
30     */
31    // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
32    public function __invoke(Request $request, Response $response, array $args): Response
33    {
34        try {
35            $command = $this->commandFactory->fromRequest($request);
36            $this->districtService->add($command);
37            $this->session->set("success.message", "District data saved successfully.");
38            $this->session->delete("form.add.values");
39            $this->session->delete("form.add.errors");
40            $url = $this->routeParser->relativeUrlFor("list");
41            return $this->responseFactory->createResponse(StatusCode::STATUS_FOUND)->withHeader("Location", $url);
42        } catch (ValidationException $exception) {
43            $this->session->set("form.add.values", $request->getParsedBody());
44            $this->session->set("form.add.error.message", "An error occured while saving district data.");
45            $this->session->set("form.add.errors", array_fill_keys($exception->getErrors(), true));
46            $url = $this->routeParser->relativeUrlFor("add");
47            return $this->responseFactory->createResponse(StatusCode::STATUS_FOUND)->withHeader("Location", $url);
48        }
49    }
50}