JsonObjectSerializer::serialize()   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
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