JsonObjectSerializer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 12
c 1
b 0
f 0
dl 0
loc 38
ccs 16
cts 16
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A serializeMultiple() 0 4 1
A __construct() 0 5 1
A unserialize() 0 4 1
A unserializeMultiple() 0 4 1
A serialize() 0 3 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
13
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
14
use Symfony\Component\Serializer\Serializer;
15
16
/**
17
 * JsonObjectSerializer serializes objects in JSON format and vice versa.
18
 */
19
final class JsonObjectSerializer implements ObjectSerializerInterface
20
{
21
    use ObjectSerializerTrait;
22
23
    /**
24
     * @param int $options The encoding options.
25
     *
26
     * @see http://www.php.net/manual/en/function.json-encode.php
27
     */
28 7
    public function __construct(int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
29
    {
30 7
        $this->serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder(
31 7
            new JsonEncode([JsonEncode::OPTIONS => $options]),
32 7
            new JsonDecode([JsonDecode::ASSOCIATIVE => true]),
33
        )]);
34 7
    }
35
36 1
    public function serialize(object $object): string
37
    {
38 1
        return $this->serializer->serialize($object, JsonEncoder::FORMAT);
39
    }
40
41 2
    public function serializeMultiple(array $objects): string
42
    {
43 2
        $this->checkArrayObjects($objects);
44 1
        return $this->serializer->serialize($objects, JsonEncoder::FORMAT);
45
    }
46
47 3
    public function unserialize(string $value, string $class): object
48
    {
49 3
        $decodedValue = $this->checkAndDecodeData($value, $class, JsonEncoder::FORMAT);
50 2
        return $this->denormalizeObject($decodedValue, $class);
51
    }
52
53 3
    public function unserializeMultiple(string $value, string $class): array
54
    {
55 3
        $decodedValue = $this->checkAndDecodeData($value, $class, JsonEncoder::FORMAT);
56 2
        return $this->denormalizeObjects($decodedValue, $class);
57
    }
58
}
59