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
|
|
|
|
20
|
|
|
public function normalize($data, $format = null, array $context = []) |
21
|
|
|
{ |
22
|
|
|
$normalizedData = parent::normalize($data, $format, $context); |
23
|
|
|
|
24
|
|
|
if (is_object($data)) { |
25
|
|
|
$typeData = [self::KEY_TYPE => get_class($data)]; |
26
|
|
|
$valueData = is_scalar($normalizedData) ? [self::KEY_SCALAR => $normalizedData] : $normalizedData; |
27
|
|
|
$normalizedData = array_merge($typeData, $valueData); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return $normalizedData; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function denormalize($data, $class, $format = null, array $context = []) |
34
|
|
|
{ |
35
|
|
|
if (is_array($data) && (isset($data[self::KEY_TYPE]))) { |
36
|
|
|
$type = $data[self::KEY_TYPE]; |
37
|
|
|
unset($data[self::KEY_TYPE]); |
38
|
|
|
|
39
|
|
|
$data = $data[self::KEY_SCALAR] ?? $data; |
40
|
|
|
|
41
|
|
|
return parent::denormalize($data, $type, $format, $context); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if (is_iterable($data)) { |
45
|
|
|
$class = ($class === '') ? 'stdClass' : $class; |
46
|
|
|
$arrayOfDocuments = true; |
47
|
|
|
foreach ($data as $row) { |
|
|
|
|
48
|
|
|
if (!is_array($row)) { |
49
|
|
|
$arrayOfDocuments = false; |
50
|
|
|
break; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if (!isset($row[self::KEY_TYPE])) { |
54
|
|
|
$arrayOfDocuments = false; |
55
|
|
|
break; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if ($arrayOfDocuments) { |
60
|
|
|
return parent::denormalize($data, $class.'[]', $format, $context); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return parent::denormalize($data, $class, $format, $context); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
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.