Test Failed
Branch v0.2 (3f77aa)
by Freddie
07:42 queued 01:11
created

HandleBadRequests   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A createResponseBody() 0 13 2
A __invoke() 0 17 3
A writeViolationsToResponse() 0 10 2
A __construct() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace Simplex\Quickstart\Shared\HttpMiddleware;
4
5
use JMS\Serializer\SerializerInterface;
6
use Lukasoppermann\Httpstatus\Httpstatuscodes;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Simplex\Exception\ResourceNotFoundException;
10
use Simplex\Quickstart\Shared\Exception\BadRequestException;
11
use Symfony\Component\Validator\ConstraintViolation;
12
use Symfony\Component\Validator\ConstraintViolationListInterface;
13
14
class HandleBadRequests
15
{
16
    const JSON_FORMAT = 'json';
17
18
    const PROPERTY_KEY = 'property';
19
    const MESSAGE_KEY = 'message';
20
21
    /** @var SerializerInterface */
22
    private $serializer;
23
24
    public function __construct(SerializerInterface $serializer)
25
    {
26
        $this->serializer = $serializer;
27
    }
28
29
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
30
    {
31
        try {
32
33
            $response = $next($request, $response);
34
35
        } catch (BadRequestException $exception) {
36
37
            $response = $response->withStatus(Httpstatuscodes::HTTP_BAD_REQUEST);
38
            $this->writeViolationsToResponse($exception, $response);
39
40
        } catch (ResourceNotFoundException $exception) {
41
42
            $response = $response->withStatus(Httpstatuscodes::HTTP_NOT_FOUND);
43
        }
44
45
        return $next($request, $response);
46
    }
47
48
    private function writeViolationsToResponse(BadRequestException $exception, ResponseInterface $response): void
49
    {
50
        $violations = $exception->getViolations();
51
52
        if (null === $violations) {
53
            return;
54
        }
55
56
        $response->getBody()->write(
57
            $this->serializer->serialize($this->createResponseBody($violations), self::JSON_FORMAT)
58
        );
59
    }
60
61
    private function createResponseBody(ConstraintViolationListInterface $violations): array
62
    {
63
        $body = [];
64
65
        /** @var ConstraintViolation $violation */
66
        foreach ($violations as $violation) {
67
            $body[] = [
68
                self::PROPERTY_KEY => $violation->getPropertyPath(),
69
                self::MESSAGE_KEY => $violation->getMessage(),
70
            ];
71
        }
72
73
        return $body;
74
    }
75
}
76