1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* (c) Kévin Dunglas <[email protected]> |
5
|
|
|
* |
6
|
|
|
* This source file is subject to the MIT license that is bundled |
7
|
|
|
* with this source code in the file LICENSE. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Dunglas\DoctrineJsonOdm; |
11
|
|
|
|
12
|
|
|
use Symfony\Component\Serializer\Serializer as BaseSerializer; |
13
|
|
|
|
14
|
|
|
final class Serializer extends BaseSerializer |
15
|
|
|
{ |
16
|
|
|
private const KEY_TYPE = '#type'; |
17
|
|
|
private const KEY_SCALAR = '#scalar'; |
18
|
|
|
|
19
|
|
|
public function normalize($data, $format = null, array $context = []) |
20
|
|
|
{ |
21
|
|
|
$normalizedData = parent::normalize($data, $format, $context); |
22
|
|
|
|
23
|
|
|
if (is_object($data)) { |
24
|
|
|
$typeData = [self::KEY_TYPE => get_class($data)]; |
25
|
|
|
$valueData = is_scalar($normalizedData) ? [self::KEY_SCALAR => $normalizedData] : $normalizedData; |
26
|
|
|
$normalizedData = array_merge($typeData, $valueData); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
return $normalizedData; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function denormalize($data, $class, $format = null, array $context = []) |
33
|
|
|
{ |
34
|
|
|
if (is_array($data) && (isset($data[self::KEY_TYPE]))) { |
35
|
|
|
$type = $data[self::KEY_TYPE]; |
36
|
|
|
unset($data[self::KEY_TYPE]); |
37
|
|
|
|
38
|
|
|
$data = $data[self::KEY_SCALAR] ?? $data; |
39
|
|
|
$data = $this->denormalize($data, $type, $format, $context); |
40
|
|
|
|
41
|
|
|
return parent::denormalize($data, $type, $format, $context); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if (is_iterable($data)) { |
45
|
|
|
$class = ($class === '') ? 'stdClass' : $class; |
46
|
|
|
|
47
|
|
|
return parent::denormalize($data, $class.'[]', $format, $context); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $data; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|