|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Serializer; |
|
6
|
|
|
|
|
7
|
|
|
use Symfony\Component\Serializer\Encoder\XmlEncoder; |
|
8
|
|
|
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
|
9
|
|
|
use Symfony\Component\Serializer\Serializer; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* XmlObjectSerializer serializes objects in XML format and vice versa. |
|
13
|
|
|
*/ |
|
14
|
|
|
final class XmlObjectSerializer implements ObjectSerializerInterface |
|
15
|
|
|
{ |
|
16
|
|
|
use ObjectSerializerTrait; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @param string $rootTag The name of the root element. |
|
20
|
|
|
* @param string $version The XML version. |
|
21
|
|
|
* @param string $encoding The XML encoding. |
|
22
|
|
|
*/ |
|
23
|
5 |
|
public function __construct(string $rootTag = 'response', string $version = '1.0', string $encoding = 'UTF-8') |
|
24
|
|
|
{ |
|
25
|
5 |
|
$this->serializer = new Serializer([new ObjectNormalizer()], [new XmlEncoder([ |
|
26
|
5 |
|
XmlEncoder::ROOT_NODE_NAME => $rootTag, |
|
27
|
5 |
|
XmlEncoder::VERSION => $version, |
|
28
|
5 |
|
XmlEncoder::ENCODING => $encoding, |
|
29
|
|
|
])]); |
|
30
|
5 |
|
} |
|
31
|
|
|
|
|
32
|
4 |
|
public function serialize(object $object): string |
|
33
|
|
|
{ |
|
34
|
4 |
|
return $this->serializer->serialize($object, XmlEncoder::FORMAT); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
1 |
|
public function serializeMultiple(array $objects): string |
|
38
|
|
|
{ |
|
39
|
1 |
|
$this->checkArrayObjects($objects); |
|
40
|
1 |
|
return $this->serializer->serialize($objects, XmlEncoder::FORMAT); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
1 |
|
public function unserialize(string $value, string $class): object |
|
44
|
|
|
{ |
|
45
|
1 |
|
$decodedValue = $this->checkAndDecodeData($value, $class, XmlEncoder::FORMAT); |
|
46
|
1 |
|
return $this->denormalizeObject($decodedValue, $class); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
1 |
|
public function unserializeMultiple(string $value, string $class): array |
|
50
|
|
|
{ |
|
51
|
1 |
|
$decodedValue = $this->checkAndDecodeData($value, $class, XmlEncoder::FORMAT); |
|
52
|
1 |
|
return $this->denormalizeObjects($decodedValue, $class); |
|
|
|
|
|
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
In the issue above, the returned value is violating the contract defined by the mentioned interface.
Let's take a look at an example: