1
|
|
|
<?php |
2
|
|
|
/****************************************************************************** |
3
|
|
|
* Copyright (c) 2017 Constantin Galbenu <[email protected]> * |
4
|
|
|
******************************************************************************/ |
5
|
|
|
|
6
|
|
|
namespace Gica\Serialize\ObjectSerializer; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
use Gica\Serialize\ObjectSerializer\Exception\ValueNotSerializable; |
10
|
|
|
|
11
|
|
|
class ObjectSerializer |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var Serializer |
15
|
|
|
*/ |
16
|
|
|
private $serializer; |
17
|
|
|
|
18
|
6 |
|
public function __construct( |
19
|
|
|
Serializer $serializer |
20
|
|
|
) |
21
|
|
|
{ |
22
|
6 |
|
$this->serializer = $serializer; |
23
|
6 |
|
} |
24
|
|
|
|
25
|
6 |
|
public function convert($anything) |
26
|
|
|
{ |
27
|
6 |
|
if (is_array($anything)) { |
28
|
2 |
|
return array_map(function ($item) { |
29
|
2 |
|
return $this->convert($item); |
30
|
2 |
|
}, $anything); |
31
|
|
|
} |
32
|
|
|
|
33
|
6 |
|
if (!is_object($anything)) { |
34
|
2 |
|
return $anything; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
try { |
38
|
5 |
|
return $this->serializer->serialize($anything); |
39
|
5 |
|
} catch (ValueNotSerializable $exception) { |
40
|
|
|
//continue normally |
41
|
|
|
} |
42
|
|
|
|
43
|
5 |
|
$class = new \ReflectionClass($anything); |
44
|
|
|
|
45
|
5 |
|
$properties = $this->getClassProperties($class); |
46
|
|
|
|
47
|
|
|
$result = [ |
48
|
5 |
|
'@classes' => [], |
49
|
|
|
]; |
50
|
|
|
|
51
|
5 |
|
foreach ($properties as $property) { |
52
|
5 |
|
$property->setAccessible(true); |
53
|
5 |
|
$unserializedValue = $property->getValue($anything); |
54
|
5 |
|
$value = $unserializedValue; |
55
|
5 |
|
if (is_object($unserializedValue) || is_array($unserializedValue)) { |
56
|
2 |
|
$value = $this->convert($unserializedValue); |
57
|
|
|
} |
58
|
5 |
|
$result[$property->getName()] = $value; |
59
|
5 |
|
if (is_object($unserializedValue)) { |
60
|
5 |
|
$result['@classes'][$property->getName()] = get_class($unserializedValue); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
if (empty($result['@classes'])) { |
65
|
5 |
|
unset($result['@classes']); |
66
|
|
|
} |
67
|
|
|
|
68
|
5 |
|
return $result; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param \ReflectionClass $class |
73
|
|
|
* @return \ReflectionProperty[] |
74
|
|
|
*/ |
75
|
5 |
|
private function getClassProperties(\ReflectionClass $class) |
76
|
|
|
{ |
77
|
5 |
|
$properties = $class->getProperties(); |
78
|
5 |
|
if (!$class->getParentClass()) { |
79
|
5 |
|
return $properties; |
80
|
|
|
} |
81
|
1 |
|
$parentProperties = $this->getClassProperties($class->getParentClass()); |
82
|
1 |
|
return array_merge($properties, $parentProperties); |
83
|
|
|
} |
84
|
|
|
} |