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

SymfonySerializerAdapter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.74%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 46
ccs 18
cts 19
cp 0.9474
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A deserialize() 0 6 1
A serialize() 0 6 1
A convertContext() 0 16 3
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