-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathObjectSerializer.php
More file actions
302 lines (266 loc) · 10.5 KB
/
ObjectSerializer.php
File metadata and controls
302 lines (266 loc) · 10.5 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
/**
* Fingerprint Pro Server API.
*
* Fingerprint Pro Server API allows you to get information about visitors and about individual events in a server environment. It can be used for data exports, decision-making, and data analysis scenarios. Server API is intended for server-side usage, it's not intended to be used from the client side, whether it's a browser or a mobile device.
*/
namespace Fingerprint\ServerAPI;
use DateTime;
use DateTimeInterface;
use Exception;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use stdClass;
class ObjectSerializer
{
/**
* Serialize data.
*
* @param mixed $data the data to serialize
* @param string|null $format the format of the Swagger type of the data
*
* @return array|bool|object|string serialized form of $data
*/
public static function sanitizeForSerialization(mixed $data, ?string $format = null): array|bool|object|string
{
if (is_scalar($data) || null === $data) {
return $data;
}
if ($data instanceof DateTime) {
return ('date' === $format) ? $data->format('Y-m-d') : $data->format(DateTimeInterface::ATOM);
}
if (is_array($data)) {
foreach ($data as $property => $value) {
if (is_scalar($value)) {
$data[$property] = $value;
} else {
$data[$property] = self::sanitizeForSerialization($value);
}
}
return $data;
}
if ($data instanceof stdClass) {
foreach ($data as $property => $value) {
if (is_scalar($value)) {
$data->{$property} = $value;
} else {
$data->{$property} = self::sanitizeForSerialization($value);
}
}
return $data;
}
if (is_object($data)) {
$class = get_class($data);
if (enum_exists($class)) {
return $data->value;
}
$values = [];
$formats = $data::swaggerFormats();
foreach ($data::swaggerTypes() as $property => $swaggerType) {
$getter = $data::getters()[$property];
$value = $data->{$getter}();
if (null !== $value
&& !in_array($swaggerType, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)
&& method_exists($swaggerType, 'getAllowableEnumValues')
&& !in_array($value, $swaggerType::getAllowableEnumValues())) {
$imploded = implode("', '", $swaggerType::getAllowableEnumValues());
throw new InvalidArgumentException("Invalid value for enum '$swaggerType', must be one of: '$imploded'");
}
if (null !== $value) {
if (is_scalar($value)) {
$values[$data::attributeMap()[$property]] = $value;
} elseif ('tag' === $property && empty($value)) {
$values[$data::attributeMap()[$property]] = new stdClass();
} else {
$values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $formats[$property]);
}
}
}
return (object) $values;
}
return (string) $data;
}
/**
* Take value and turn it into a string suitable for inclusion in
* the path, by url-encoding.
*
* @param string $value a string which will be part of the path
*
* @return string the serialized object
*/
public static function toPathValue(string $value): string
{
return rawurlencode(self::toString($value));
}
/**
* Take value and turn it into a string suitable for inclusion in
* the query, by imploding comma-separated if it's an object.
* If it's a string, pass through unchanged. It will be url-encoded
* later.
*
* @param DateTime|string|string[] $object an object to be serialized to a string
* @param string|null $format the format of the parameter
*
* @return array|string the serialized object
*/
public static function toQueryValue(array|bool|DateTime|string $object, ?string $format = null): array|string
{
if (is_array($object)) {
return match ($format) {
'multi' => $object,
'ssv' => implode(' ', $object),
'tsv' => implode("\t", $object),
'pipes' => implode('|', $object),
default => implode(',', $object),
};
}
if (is_bool($object)) {
return $object ? 'true' : 'false';
}
return self::toString($object, $format);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the parameter. If it's a string, pass through unchanged
* If it's a datetime object, format it in RFC3339
* If it's a date, format it in Y-m-d.
*
* @param DateTime|string $value the value of the parameter
* @param string|null $format the format of the parameter
*
* @return string the header string
*/
public static function toString(DateTime|string $value, ?string $format = null): string
{
if ($value instanceof DateTime) {
return ('date' === $format) ? $value->format('Y-m-d') : $value->format(DateTimeInterface::ATOM);
}
return $value;
}
/**
* Deserialize a JSON string into an object.
*
* @param string $class class name is passed as a string
*
* @throws Exception
*/
public static function deserialize(ResponseInterface $response, string $class): mixed
{
$data = $response->getBody()->getContents();
$response->getBody()->rewind();
return self::mapToClass($data, $class, $response);
}
/**
* @throws \DateMalformedStringException
* @throws SerializationException
* @noinspection PhpFullyQualifiedNameUsageInspection
*/
protected static function mapToClass(mixed $data, string $class, ResponseInterface $response): mixed
{
if ('string' === gettype($data)) {
$data = json_decode($data, false);
}
$instance = new $class();
foreach ($instance::swaggerTypes() as $property => $type) {
$propertySetter = $instance::setters()[$property];
if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) {
continue;
}
$propertyValue = $data->{$instance::attributeMap()[$property]};
if (isset($propertyValue)) {
$instance->{$propertySetter}(self::castData($propertyValue, $type, $response));
}
}
return $instance;
}
/**
* @throws \DateMalformedStringException
* @throws SerializationException
* @noinspection PhpMultipleClassDeclarationsInspection
* @noinspection PhpUndefinedMethodInspection
* @noinspection PhpFullyQualifiedNameUsageInspection
*/
protected static function castData(mixed $data, string $class, ResponseInterface $response): mixed
{
if (null === $data) {
return null;
}
if (str_starts_with($class, 'map[')) { // for associative array e.g. map[string,int]
$inner = substr($class, 4, -1);
$deserialized = [];
if (false !== strrpos($inner, ',')) {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::castData($value, $subClass, $response);
}
}
return $deserialized;
}
if (0 === strcasecmp(substr($class, -2), '[]')) {
$subClass = substr($class, 0, -2);
$values = [];
foreach ($data as $value) {
$values[] = self::castData($value, $subClass, $response);
}
return $values;
}
if ('mixed' === $class) {
if ($data instanceof stdClass) {
if (empty(get_object_vars($data))) {
return null;
}
return (array) $data;
}
return $data;
}
if ('object' === $class || 'array' === $class) {
settype($data, 'array');
return $data;
}
if ('\DateTime' === $class) {
// Some API's return an invalid, empty string as a
// date-time property. DateTime::__construct() will return
// the current time for empty input which is probably not
// what is meant. The invalid empty string is probably to
// be interpreted as a missing field/value. Let's handle
// this graceful.
if (!empty($data)) {
return new DateTime($data);
}
return null;
}
if (in_array($class, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) {
$originalData = $data;
$normalizedClass = strtolower($class);
switch ($normalizedClass) {
case 'int':
$normalizedClass = 'integer';
break;
case 'bool':
$normalizedClass = 'boolean';
break;
}
if ('float' === $normalizedClass && is_numeric($originalData)) {
return (float) $originalData;
}
if ('string' === $normalizedClass && is_object($data)) {
throw new SerializationException($response);
}
settype($data, $class);
if (gettype($data) === $normalizedClass) {
return $data;
}
throw new SerializationException($response);
} elseif (enum_exists($class)) {
try {
return $class::from($data);
} catch (\ValueError) {
$allowedValues = array_map(fn ($case) => $case->value, $class::cases());
$imploded = implode("', '", $allowedValues);
throw new InvalidArgumentException("Invalid value '$data' for enum '$class', must be one of: '$imploded'");
}
}
return self::mapToClass($data, $class, $response);
}
}