FormExceptionNormalizer::supportsNormalization()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
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