1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Serializer; |
6
|
|
|
|
7
|
|
|
use Symfony\Component\Serializer\Encoder\JsonDecode; |
8
|
|
|
use Symfony\Component\Serializer\Encoder\JsonEncode; |
9
|
|
|
use Symfony\Component\Serializer\Encoder\JsonEncoder; |
10
|
|
|
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
11
|
|
|
use Symfony\Component\Serializer\Serializer; |
12
|
|
|
|
13
|
|
|
use const JSON_UNESCAPED_SLASHES; |
14
|
|
|
use const JSON_UNESCAPED_UNICODE; |
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
|
|
|
* @see http://www.php.net/manual/en/function.json-encode.php |
26
|
|
|
*/ |
27
|
2 |
|
public function __construct(int $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) |
28
|
|
|
{ |
29
|
2 |
|
$this->serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder( |
30
|
2 |
|
new JsonEncode([JsonEncode::OPTIONS => $options]), |
31
|
2 |
|
new JsonDecode([JsonDecode::ASSOCIATIVE => true]), |
32
|
|
|
)]); |
33
|
2 |
|
} |
34
|
|
|
|
35
|
1 |
|
public function serialize(object $object): string |
36
|
|
|
{ |
37
|
1 |
|
return $this->serializer->serialize($object, JsonEncoder::FORMAT); |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
public function serializeMultiple(array $objects): string |
41
|
|
|
{ |
42
|
1 |
|
$this->checkArrayObjects($objects); |
43
|
1 |
|
return $this->serializer->serialize($objects, JsonEncoder::FORMAT); |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
public function unserialize(string $value, string $class): object |
47
|
|
|
{ |
48
|
1 |
|
$decodedValue = $this->checkAndDecodeData($value, $class, JsonEncoder::FORMAT); |
49
|
1 |
|
return $this->denormalizeObject($decodedValue, $class); |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
public function unserializeMultiple(string $value, string $class): array |
53
|
|
|
{ |
54
|
1 |
|
$decodedValue = $this->checkAndDecodeData($value, $class, JsonEncoder::FORMAT); |
55
|
1 |
|
return $this->denormalizeObjects($decodedValue, $class); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: