appendCollectionAttributes()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 4
crap 2
1
<?php
2
3
declare(strict_types = 1);
4
5
/*
6
 * This file is part of the FiveLab Resource package
7
 *
8
 * (c) FiveLab
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code
12
 */
13
14
namespace FiveLab\Component\Resource\Serializer\Normalizer;
15
16
use FiveLab\Component\Resource\Resource\Error\ErrorCollection;
17
use FiveLab\Component\Resource\Resource\Error\ErrorResource;
18
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
19
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
20
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
21
22
/**
23
 * Normalizer for normalize error collection.
24
 *
25
 * @author Vitaliy Zhuk <[email protected]>
26
 */
27
class ErrorCollectionObjectNormalizer implements NormalizerInterface, NormalizerAwareInterface
28
{
29
    use NormalizerAwareTrait;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 2
    public function supportsNormalization($data, $format = null): bool
35
    {
36 2
        return $data instanceof ErrorCollection;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     *
42
     * @param ErrorCollection $object
43
     */
44 1
    public function normalize($object, $format = null, array $context = [])
45
    {
46 1
        $normalized = ['errors' => []];
47
48 1
        foreach ($object as $innerError) {
49 1
            $normalized['errors'][] = $this->normalizer->normalize($innerError, $format, $context);
50
        }
51
52 1
        $normalized = $this->appendCollectionAttributes($normalized, $object, (string) $format, $context);
53
54 1
        return $normalized;
55
    }
56
57
    /**
58
     * Append collection attributes to
59
     *
60
     * @param array           $data
61
     * @param ErrorCollection $error
62
     * @param string          $format
63
     * @param array           $context
64
     *
65
     * @return array
66
     */
67 1
    public function appendCollectionAttributes(array $data, ErrorCollection $error, string $format, array $context): array
68
    {
69 1
        $innerError = new ErrorResource(
70 1
            $error->getMessage(),
71 1
            $error->getReason(),
72 1
            $error->getPath(),
73 1
            $error->getAttributes(),
74 1
            $error->getIdentifier()
75
        );
76
77 1
        foreach ($error->getRelations() as $relation) {
78 1
            $innerError->addRelation($relation);
79
        }
80
81 1
        $normalizedInnerError = $this->normalizer->normalize($innerError, $format, $context);
82
83 1
        return \array_merge($normalizedInnerError, $data);
84
    }
85
}
86