Passed
Push — master ( c9c108...62a3cd )
by Pieter
03:55
created

ValidationExceptionNormalizer::normalize()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 8
c 1
b 0
f 1
nc 1
nop 3
dl 0
loc 14
rs 10
1
<?php
2
3
4
namespace W2w\Laravel\Apie\Plugins\IlluminateTranslation\Normalizers;
5
6
use Illuminate\Contracts\Translation\Translator;
7
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
8
use W2w\Lib\ApieObjectAccessNormalizer\Errors\ErrorBagField;
9
use W2w\Lib\ApieObjectAccessNormalizer\Exceptions\ValidationException;
10
11
class ValidationExceptionNormalizer implements NormalizerInterface
12
{
13
    use SharedTranslatorTrait;
14
15
    /**
16
     * @var LocationableExceptionNormalizer
17
     */
18
    private $locationableExceptionNormalizer;
19
20
    public function __construct(LocationableExceptionNormalizer $locationableExceptionNormalizer, Translator $translator)
21
    {
22
        $this->locationableExceptionNormalizer = $locationableExceptionNormalizer;
23
        $this->translator = $translator;
24
    }
25
26
    /**
27
     * {@inheritDoc}
28
     */
29
    public function normalize($object, string $format = null, array $context = [])
30
    {
31
        /** @var ValidationException $object */
32
        $data = $this->locationableExceptionNormalizer->normalize($object, $format, $context);
33
        $data['errors'] = $object->getErrorBag()->getErrors(
34
            function (ErrorBagField $field) {
35
                $info = $field->getLocalizationInfo();
36
                if (!$info) {
37
                    return $field->getMessage();
38
                }
39
                return $this->translate($info);
40
            }
41
        );
42
        return $data;
43
    }
44
45
    /**
46
     * {@inheritDoc}
47
     */
48
    public function supportsNormalization($data, string $format = null)
49
    {
50
        return $data instanceof ValidationException;
51
    }
52
}
53