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

JsonEncoder::decode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 3
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