Passed
Push — master ( e1125f...803f3c )
by Daniel
02:06
created

ValidationMiddleware::transform()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 4
nop 1
dl 0
loc 24
ccs 14
cts 14
cp 1
crap 4
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace App\Middleware;
4
5
use Psr\Http\Message\ResponseFactoryInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use Symfony\Component\Validator\ConstraintViolation;
11
use Symfony\Component\Validator\Exception\ValidationFailedException;
12
13
final class ValidationMiddleware implements MiddlewareInterface
14
{
15
    private ResponseFactoryInterface $responseFactory;
16
17 10
    public function __construct(ResponseFactoryInterface $responseFactory)
18
    {
19 10
        $this->responseFactory = $responseFactory;
20
    }
21
22 10
    public function process(
23
        ServerRequestInterface $request,
24
        RequestHandlerInterface $handler
25
    ): ResponseInterface {
26
        try {
27 10
            return $handler->handle($request);
28 3
        } catch (ValidationFailedException $exception) {
29 2
            $response = $this->responseFactory->createResponse();
30 2
            $data = $this->transform($exception);
31 2
            $json = (string)json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
32 2
            $response->getBody()->write($json);
33
34 2
            return $response
35 2
                ->withStatus(422)
36 2
                ->withHeader('Content-Type', 'application/json');
37
        }
38
    }
39
40 2
    private function transform(ValidationFailedException $exception): array
41
    {
42 2
        $error = [];
43 2
        $violations = $exception->getViolations();
44
45 2
        if ($exception->getValue()) {
46 2
            $error['message'] = $exception->getValue();
47
        }
48
49 2
        if ($violations->count()) {
50 2
            $details = [];
51
52
            /** @var ConstraintViolation $violation */
53 2
            foreach ($violations as $violation) {
54 2
                $details[] = [
55 2
                    'message' => $violation->getMessage(),
56 2
                    'field' => $violation->getPropertyPath(),
57 2
                ];
58
            }
59
60 2
            $error['details'] = $details;
61
        }
62
63 2
        return ['error' => $error];
64
    }
65
}
66