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
|
|
|
|
40
|
|
|
return parent::denormalize($data, $type, $format, $context); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if (is_iterable($data)) { |
44
|
|
|
$class = ($class === '') ? 'stdClass' : $class; |
45
|
|
|
$arrayOfDocuments = true; |
46
|
|
|
foreach ($data as $row) { |
|
|
|
|
47
|
|
|
if (!is_array($row)) { |
48
|
|
|
$arrayOfDocuments = false; |
49
|
|
|
break; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (!isset($row[self::KEY_TYPE])) { |
53
|
|
|
$arrayOfDocuments = false; |
54
|
|
|
break; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if ($arrayOfDocuments) { |
59
|
|
|
return parent::denormalize($data, $class.'[]', $format, $context); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return parent::denormalize($data, $class, $format, $context); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
There are different options of fixing this problem.
If you want to be on the safe side, you can add an additional type-check:
If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:
Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.