forked from matthiasnoback/naive-serializer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonSerializer.php
More file actions
171 lines (143 loc) · 5.55 KB
/
JsonSerializer.php
File metadata and controls
171 lines (143 loc) · 5.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
<?php
declare(strict_types = 1);
namespace NaiveSerializer;
use Assert\Assertion;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use phpDocumentor\Reflection\DocBlockFactory;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Array_;
use phpDocumentor\Reflection\Types\Boolean;
use phpDocumentor\Reflection\Types\ContextFactory;
use phpDocumentor\Reflection\Types\Float_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Object_;
use phpDocumentor\Reflection\Types\String_;
final class JsonSerializer
{
private $contextFactory;
private $docblockFactory;
private $typeResolver;
public function __construct()
{
$this->contextFactory = new ContextFactory();
$this->docblockFactory = DocBlockFactory::createInstance();
$this->typeResolver = new TypeResolver();
}
public function deserialize(string $type, string $jsonEncodedData)
{
$resolvedType = $this->typeResolver->resolve($type);
return self::restoreDataStructure($resolvedType, $this->jsonDecode($jsonEncodedData));
}
private function restoreDataStructure(Type $type, $data)
{
if ($data === null) {
// TODO verify that null is allowed
return null;
}
if ($type instanceof String_) {
return (string)$data;
}
if ($type instanceof Integer) {
return (integer)$data;
}
if ($type instanceof Boolean) {
return (boolean)$data;
}
if ($type instanceof Float_) {
return (float)$data;
}
if ($type instanceof Object_) {
Assertion::isArray($data);
$reflection = new \ReflectionClass((string)$type);
if (!$reflection->isUserDefined()) {
throw new \LogicException(sprintf('Class "%s" is not user-defined', $type));
}
$object = $reflection->newInstanceWithoutConstructor();
foreach ($reflection->getProperties() as $property) {
if (!array_key_exists($property->getName(), $data)) {
continue;
}
$propertyType = $this->resolvePropertyType($property, $reflection);
$property->setAccessible(true);
$property->setValue($object, self::restoreDataStructure($propertyType, $data[$property->getName()]));
}
return $object;
}
if ($type instanceof Array_) {
$processed = [];
foreach ($data as $key => $elementData) {
$processed[$key] = self::restoreDataStructure($type->getValueType(), $elementData);
}
return $processed;
}
throw new \LogicException('Unsupported type: ' . get_class($type));
}
public function serialize($rawData)
{
return json_encode($this->extractSerializableDataFrom($rawData), JSON_PRETTY_PRINT);
}
private function extractSerializableDataFrom($something)
{
if (is_object($something)) {
$data = [];
$reflection = new \ReflectionClass(get_class($something));
if (!$reflection->isUserDefined()) {
throw new \LogicException(sprintf('Class "%s" is not user-defined', $reflection->getName()));
}
foreach ($reflection->getProperties() as $property) {
$property->setAccessible(true);
$data[$property->getName()] = $this->extractSerializableDataFrom($property->getValue($something));
}
return $data;
}
if (is_array($something)) {
$data = [];
foreach ($something as $key => $element) {
$data[$key] = $this->extractSerializableDataFrom($element);
}
return $data;
}
if (is_scalar($something) || $something === null) {
return $something;
}
throw new \LogicException(sprintf(
'Unsupported type: "%s" (%s). You can only serialize objects, arrays and scalar values.',
gettype($something),
var_export($something, true)
));
}
private function resolvePropertyType(\ReflectionProperty $property, \ReflectionClass $class) : Type
{
$fileName = $class->getFileName();
Assertion::file($fileName, sprintf(
'Class "%s" has no source file, maybe it is a PHP built-in class?',
$class->getName()
));
$context = $this->contextFactory->createForNamespace(
$class->getNamespaceName(),
file_get_contents($fileName)
);
$docComment = $property->getDocComment();
Assertion::notEmpty($docComment, sprintf('You need to add a docblock to property "%s"', $property->getName()));
$docblock = $this->docblockFactory->create($docComment, $context);
$varTags = $docblock->getTagsByName('var');
Assertion::count(
$varTags,
1,
sprintf('You need to add an @var annotation to property "%s"', $property->getName())
);
/** @var Var_[] $varTags */
$propertyType = $varTags[0]->getType();
return $propertyType;
}
private function jsonDecode(string $jsonEncodedData) : array
{
$decoded = json_decode($jsonEncodedData, true);
if ($decoded === null && json_last_error()) {
throw new \LogicException('You provided invalid JSON: ' . json_last_error_msg());
}
return $decoded;
}
}