Completed
Pull Request — 2.x (#2288)
by Guilhem
17:20
created

SymfonySerializerAdapter::convertContext()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 10
cp 0.9
rs 9.7333
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3.009
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
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
namespace FOS\RestBundle\Serializer;
13
14
use FOS\RestBundle\Context\Context;
15
use Symfony\Component\Serializer\SerializerInterface;
16
17
/**
18
 * Adapter to plug the Symfony serializer into the FOSRestBundle Serializer API.
19
 *
20
 * @author Christian Flothmann <[email protected]>
21
 */
22
final class SymfonySerializerAdapter implements Serializer
23
{
24
    private $serializer;
25
26 12
    public function __construct(SerializerInterface $serializer)
27
    {
28 12
        $this->serializer = $serializer;
29 12
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 9
    public function serialize($data, string $format, Context $context): string
35
    {
36 9
        $newContext = $this->convertContext($context);
37
38 9
        return $this->serializer->serialize($data, $format, $newContext);
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 1
    public function deserialize(string $data, string $type, string $format, Context $context)
45
    {
46 1
        $newContext = $this->convertContext($context);
47
48 1
        return $this->serializer->deserialize($data, $type, $format, $newContext);
49
    }
50
51 10
    private function convertContext(Context $context): array
52
    {
53 10
        $newContext = [];
54 10
        foreach ($context->getAttributes() as $key => $value) {
55 2
            $newContext[$key] = $value;
56
        }
57
58 10
        if (null !== $context->getGroups()) {
59
            $newContext['groups'] = $context->getGroups();
60
        }
61 10
        $newContext['version'] = $context->getVersion();
62 10
        $newContext['enable_max_depth'] = $context->isMaxDepthEnabled();
63 10
        $newContext['skip_null_values'] = !$context->getSerializeNull();
64
65 10
        return $newContext;
66
    }
67
}
68