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