Passed
Push — master ( ce7fff...9920f1 )
by Alan
04:04
created

supportsNormalization()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 3
rs 10
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\GraphQl\Serializer\Exception;
15
16
use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
17
use GraphQL\Error\Error;
18
use GraphQL\Error\FormattedError;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
21
use Symfony\Component\Validator\ConstraintViolation;
22
23
/**
24
 * Normalize validation exceptions.
25
 *
26
 * @experimental
27
 *
28
 * @author Mahmood Bazdar <[email protected]>
29
 * @author Alan Poulain <[email protected]>
30
 */
31
final class ValidationExceptionNormalizer implements NormalizerInterface
32
{
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function normalize($object, $format = null, array $context = []): array
37
    {
38
        /** @var ValidationException */
39
        $validationException = $object->getPrevious();
40
        $error = FormattedError::createFromException($object);
41
        $error['message'] = $validationException->getMessage();
42
        $error['extensions']['status'] = Response::HTTP_BAD_REQUEST;
43
        $error['extensions']['category'] = 'user';
44
        $error['extensions']['violations'] = [];
45
46
        /** @var ConstraintViolation $violation */
47
        foreach ($validationException->getConstraintViolationList() as $violation) {
48
            $error['extensions']['violations'][] = [
49
                'path' => $violation->getPropertyPath(),
50
                'message' => $violation->getMessage(),
51
            ];
52
        }
53
54
        return $error;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function supportsNormalization($data, $format = null): bool
61
    {
62
        return $data instanceof Error && $data->getPrevious() instanceof ValidationException;
63
    }
64
}
65