JsonSerializer::unserialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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