JsonSerializer   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 9
c 1
b 0
f 0
dl 0
loc 28
ccs 11
cts 11
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A unserialize() 0 3 1
A serialize() 0 3 1
A __construct() 0 7 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Serializer;
6
7
use const JSON_UNESCAPED_SLASHES;
8
use const JSON_UNESCAPED_UNICODE;
9
use Symfony\Component\Serializer\Encoder\JsonDecode;
10
use Symfony\Component\Serializer\Encoder\JsonEncode;
11
use Symfony\Component\Serializer\Encoder\JsonEncoder;
12
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
13
14
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
15
use Symfony\Component\Serializer\Serializer;
16
17
/**
18
 * JsonSerializer serializes data in JSON format.
19
 */
20
final class JsonSerializer implements SerializerInterface
21
{
22
    private Serializer $serializer;
23
24
    /**
25
     * @param int $options The encoding options.
26
     *
27
     * @see http://www.php.net/manual/en/function.json-encode.php
28
     */
29 18
    public function __construct(int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
30
    {
31 18
        $this->serializer = new Serializer(
32 18
            [new JsonSerializableNormalizer(), new ObjectNormalizer()],
33 18
            [new JsonEncoder(
34 18
                new JsonEncode([JsonEncode::OPTIONS => $options]),
35 18
                new JsonDecode([JsonDecode::ASSOCIATIVE => true]),
36
            )],
37
        );
38 18
    }
39
40 10
    public function serialize($value): string
41
    {
42 10
        return $this->serializer->serialize($value, JsonEncoder::FORMAT);
43
    }
44
45 9
    public function unserialize(string $value)
46
    {
47 9
        return $this->serializer->decode($value, JsonEncoder::FORMAT);
48
    }
49
}
50