Lines 80.00% 12 / 15
Functions and Methods 0.00% 0 / 1
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
UpdateDistrictCommandFactory 80.00% 12 / 15 0.00% 0 / 1 6.29 0.00% 0 / 1
 fromRequestAndRoute 80.00% 12 / 15 0.00% 0 / 1 6.29
1<?php
2
3declare(strict_types=1);
4
5namespace Districts\Editor\UI\Factory;
6
7use Districts\Editor\Application\Command\UpdateDistrictCommand;
8use Psr\Http\Message\ServerRequestInterface as Request;
9use Slim\Exception\HttpBadRequestException;
10
11final class UpdateDistrictCommandFactory
12{
13    /**
14     * @param array<string, string> $routeArgs
15     */
16    public function fromRequestAndRoute(Request $request, array $routeArgs): UpdateDistrictCommand
17    {
18        if (!array_key_exists("id", $routeArgs)) {
19            throw new HttpBadRequestException($request);
20        }
21
22        $parsedBody = $request->getParsedBody();
23        if (!is_array($parsedBody)) {
24            throw new HttpBadRequestException($request);
25        }
26
27        if (
28            array_key_exists("name", $parsedBody)
29            && array_key_exists("area", $parsedBody)
30            && array_key_exists("population", $parsedBody)
31        ) {
32            return new UpdateDistrictCommand(
33                intval($routeArgs["id"]),
34                trim($parsedBody["name"]),
35                floatval($parsedBody["area"]),
36                intval($parsedBody["population"]),
37            );
38        }
39
40        throw new HttpBadRequestException($request);
41    }
42}