|
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
|
|
|
final class HandleBadRequests |
|
15
|
|
|
{ |
|
16
|
|
|
private const JSON_FORMAT = 'json'; |
|
17
|
|
|
|
|
18
|
|
|
private const PROPERTY_KEY = 'property'; |
|
19
|
|
|
private const MESSAGE_KEY = 'message'; |
|
20
|
|
|
|
|
21
|
|
|
/** @var SerializerInterface */ |
|
22
|
|
|
private $serializer; |
|
23
|
|
|
|
|
24
|
1 |
|
public function __construct(SerializerInterface $serializer) |
|
25
|
|
|
{ |
|
26
|
1 |
|
$this->serializer = $serializer; |
|
27
|
1 |
|
} |
|
28
|
|
|
|
|
29
|
6 |
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
|
30
|
|
|
{ |
|
31
|
|
|
try { |
|
32
|
|
|
|
|
33
|
6 |
|
$response = $next($request, $response); |
|
34
|
|
|
|
|
35
|
3 |
|
} catch (BadRequestException $exception) { |
|
36
|
|
|
|
|
37
|
3 |
|
$response = $response->withStatus(Httpstatuscodes::HTTP_BAD_REQUEST); |
|
38
|
3 |
|
$this->writeViolationsToResponse($exception, $response); |
|
39
|
|
|
|
|
40
|
|
|
} catch (ResourceNotFoundException $exception) { |
|
41
|
|
|
|
|
42
|
|
|
$response = $response->withStatus(Httpstatuscodes::HTTP_NOT_FOUND); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
6 |
|
return $next($request, $response); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
3 |
|
private function writeViolationsToResponse(BadRequestException $exception, ResponseInterface $response): void |
|
49
|
|
|
{ |
|
50
|
3 |
|
$violations = $exception->getViolations(); |
|
51
|
|
|
|
|
52
|
3 |
|
if (null === $violations) { |
|
53
|
|
|
return; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
3 |
|
$response->getBody()->write( |
|
57
|
3 |
|
$this->serializer->serialize($this->createResponseBody($violations), self::JSON_FORMAT) |
|
58
|
|
|
); |
|
59
|
3 |
|
} |
|
60
|
|
|
|
|
61
|
3 |
|
private function createResponseBody(ConstraintViolationListInterface $violations): array |
|
62
|
|
|
{ |
|
63
|
3 |
|
$body = []; |
|
64
|
|
|
|
|
65
|
|
|
/** @var ConstraintViolation $violation */ |
|
66
|
3 |
|
foreach ($violations as $violation) { |
|
67
|
3 |
|
$body[] = [ |
|
68
|
3 |
|
self::PROPERTY_KEY => $violation->getPropertyPath(), |
|
69
|
3 |
|
self::MESSAGE_KEY => $violation->getMessage(), |
|
70
|
|
|
]; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
3 |
|
return $body; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|