FormExceptionNormalizer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 23
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A supportsNormalization() 0 3 1
A normalize() 0 16 5
1
<?php
2
3
/**
4
 * This file is part of the bugloos/error-response-bundle project.
5
 * (c) Bugloos <https://bugloos.com/>
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
namespace Bugloos\ErrorResponseBundle\Normalizer;
11
12
use Bugloos\ErrorResponseBundle\Exception\FormException;
13
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
14
15
/**
16
 * @author Mojtaba Gheytasi <[email protected]>
17
 */
18
class FormExceptionNormalizer implements NormalizerInterface
19
{
20
    public function normalize($exception, $format = null, array $context = []): array
21
    {
22
        $formattedErrors = [];
23
24
        foreach ($exception->getErrors() as $error) {
25
            $cause = $error->getCause();
26
27
            if ($cause && method_exists($cause, 'getPropertyPath') && $cause->getPropertyPath()) {
28
                $path = preg_replace('/^(data.)|(.data)|(\\])|(\\[)|children/', '', $cause->getPropertyPath());
29
                $formattedErrors[$path] = $error->getMessage();
30
            } else {
31
                $formattedErrors[] = $error->getMessage();
32
            }
33
        }
34
35
        return $formattedErrors;
36
    }
37
38
    public function supportsNormalization($data, $format = null): bool
39
    {
40
        return $data instanceof FormException;
41
    }
42
}
43