Completed
Pull Request — master (#608)
by Amrouche
03:47
created

JsonEncoder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 2
cbo 3
dl 0
loc 47
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A supportsEncoding() 0 4 1
A encode() 0 4 1
A supportsDecoding() 0 4 1
A decode() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
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 ApiPlatform\Core\Serializer;
13
14
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Symfony\Component\Serializer\Encoder\DecoderInterface;
16
use Symfony\Component\Serializer\Encoder\EncoderInterface;
17
use Symfony\Component\Serializer\Encoder\JsonDecode;
18
use Symfony\Component\Serializer\Encoder\JsonEncode;
19
use Symfony\Component\Serializer\Encoder\JsonEncoder as BaseJsonEncoder;
20
21
/**
22
 * JSON-LD Encoder.
23
 *
24
 * @author Kévin Dunglas <[email protected]>
25
 */
26
final class JsonEncoder implements EncoderInterface, DecoderInterface
27
{
28
    private $format;
29
    private $jsonEncoder;
30
31
    public function __construct(string $format, BaseJsonEncoder $jsonEncoder = null)
32
    {
33
        $this->format = $format;
34
35
        // Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
36
        $this->jsonEncoder = $jsonEncoder ?: new BaseJsonEncoder(
37
            new JsonEncode(JsonResponse::DEFAULT_ENCODING_OPTIONS), new JsonDecode(true)
38
        );
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function supportsEncoding($format)
45
    {
46
        return $this->format === $format;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function encode($data, $format, array $context = [])
53
    {
54
        return $this->jsonEncoder->encode($data, $format, $context);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function supportsDecoding($format)
61
    {
62
        return $this->format === $format;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function decode($data, $format, array $context = [])
69
    {
70
        return $this->jsonEncoder->decode($data, $format, $context);
71
    }
72
}
73