forked from hellosign/hellosign-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectSerializer.mustache
525 lines (463 loc) · 17.4 KB
/
ObjectSerializer.mustache
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<?php
/**
* ObjectSerializer
*
* PHP version 7.3
*
* @category Class
* @package {{invokerPackage}}
* @author OpenAPI Generator team
* @link https://openapi-generator.tech
*/
{{>partial_header}}
/**
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
namespace {{invokerPackage}};
use {{modelPackage}}\ModelInterface;
use Psr\Http\Message;
use DateTime;
use DateTimeInterface;
use InvalidArgumentException;
use SplFileObject;
use GuzzleHttp\Psr7;
use GuzzleHttp\Utils;
/**
* ObjectSerializer Class Doc Comment
*
* @category Class
* @package {{invokerPackage}}
* @author OpenAPI Generator team
* @link https://openapi-generator.tech
*/
class ObjectSerializer
{
/** @var string */
private static $dateTimeFormat = DateTimeInterface::ATOM;
/**
* Change the date format
*
* @param string $format the new date format to use
*/
public static function setDateTimeFormat($format)
{
self::$dateTimeFormat = $format;
}
/**
* Serialize data
*
* @param mixed $data the data to serialize
* @param string $type|null the OpenAPIToolsType of the data
* @param string $format|null the format of the OpenAPITools type of the data
*
* @return scalar|object|array|null serialized form of $data
*/
public static function sanitizeForSerialization($data, string $type = null, string $format = null)
{
if (is_scalar($data) || null === $data) {
return $data;
}
if ($data instanceof \DateTime) {
return ($format === 'date') ? $data->format('Y-m-d') : $data->format(self::$dateTimeFormat);
}
if (is_array($data)) {
foreach ($data as $property => $value) {
$data[$property] = self::sanitizeForSerialization($value);
}
return $data;
}
if (is_object($data)) {
$values = [];
if ($data instanceof ModelInterface) {
$formats = $data::openAPIFormats();
foreach ($data::openAPITypes() as $property => $openAPIType) {
$getter = $data::getters()[$property];
$value = $data->$getter();
if ($value !== null && !in_array($openAPIType, [{{&primitives}}], true)) {
$callable = [$openAPIType, 'getAllowableEnumValues'];
if (is_callable($callable)) {
/** array $callable */
$allowedEnumTypes = $callable();
if (!in_array($value, $allowedEnumTypes, true)) {
$imploded = implode("', '", $allowedEnumTypes);
throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'");
}
}
}
if ($value !== null) {
$values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]);
}
}
} else if ($data instanceof SplFileObject) {
return (string) $data;
} else {
foreach($data as $property => $value) {
$values[$property] = self::sanitizeForSerialization($value);
}
}
return (object)$values;
} else {
return (string)$data;
}
}
/**
* Sanitize filename by removing path.
* e.g. ../../sun.gif becomes sun.gif
*
* @param string $filename filename to be sanitized
*
* @return string the sanitized filename
*/
public static function sanitizeFilename($filename)
{
if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) {
return $match[1];
} else {
return $filename;
}
}
/**
* Shorter timestamp microseconds to 6 digits length.
*
* @param string $timestamp Original timestamp
*
* @return string the shorten timestamp
*/
public static function sanitizeTimestamp($timestamp)
{
if (!is_string($timestamp)) return $timestamp;
return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp);
}
/**
* 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($value)
{
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 string[]|string|\DateTime $object an object to be serialized to a string
*
* @return string the serialized object
*/
public static function toQueryValue($object)
{
if (is_array($object)) {
return implode(',', $object);
} else {
return self::toString($object);
}
}
/**
* Take value and turn it into a string suitable for inclusion in
* the header. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
*
* @param string $value a string which will be part of the header
*
* @return string the header string
*/
public static function toHeaderValue($value)
{
$callable = [$value, 'toHeaderValue'];
if (is_callable($callable)) {
return $callable();
}
return self::toString($value);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the http body (form parameter). If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
*
* @param string|\SplFileObject $value the value of the form parameter
*
* @return string the form string
*/
public static function toFormValue($value)
{
if ($value instanceof \SplFileObject) {
return $value->getRealPath();
} else {
return self::toString($value);
}
}
/**
* 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 ISO8601
* If it's a boolean, convert it to "true" or "false".
*
* @param string|bool|DateTime $value the value of the parameter
*
* @return string the header string
*/
public static function toString($value)
{
if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(self::$dateTimeFormat);
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} else {
return $value;
}
}
/**
* Serialize an array to a string.
*
* @param array $collection collection to serialize to a string
* @param string $style the format use for serialization (csv,
* ssv, tsv, pipes, multi)
* @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array
*
* @return string
*/
public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false)
{
if ($allowCollectionFormatMulti && ('multi' === $style)) {
// http_build_query() almost does the job for us. We just
// need to fix the result of multidimensional arrays.
return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&'));
}
switch ($style) {
case 'pipeDelimited':
case 'pipes':
return implode('|', $collection);
case 'tsv':
return implode("\t", $collection);
case 'spaceDelimited':
case 'ssv':
return implode(' ', $collection);
case 'simple':
case 'csv':
// Deliberate fall through. CSV is default format.
default:
return implode(',', $collection);
}
}
/**
* Deserialize a JSON string into an object
*
* @param mixed $data object or primitive to be deserialized
* @param string $class class name is passed as a string
* @param string[] $httpHeaders HTTP headers
*
* @return object|array|null a single or an array of $class instances
*/
public static function deserialize($data, $class, $httpHeaders = null)
{
if (null === $data) {
return null;
}
if (strcasecmp(substr($class, -2), '[]') === 0) {
$data = is_string($data) ? json_decode($data, true) : $data;
if (!is_array($data)) {
throw new \InvalidArgumentException("Invalid array '$class'");
}
$subClass = substr($class, 0, -2);
$values = [];
foreach ($data as $key => $value) {
$values[$key] = self::deserialize($value, $subClass, null);
}
return $values;
}
if (preg_match('/^(array<|map\[)/', $class)) { // for associative array e.g. array<string,int>
$data = is_string($data) ? json_decode($data, true) : $data;
settype($data, 'array');
$inner = substr($class, 4, -1);
$deserialized = [];
if (strrpos($inner, ",") !== false) {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass, null);
}
}
return $deserialized;
}
if ($class === 'object') {
settype($data, 'array');
return $data;
} else if ($class === 'mixed') {
settype($data, gettype($data));
return $data;
}
if ($class === 'DateTime') {
// 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)) {
try {
return new \DateTime($data);
} catch (\Exception $exception) {
// Some API's return a date-time with too high nanosecond
// precision for php's DateTime to handle.
// With provided regexp 6 digits of microseconds saved
return new \DateTime(self::sanitizeTimestamp($data));
}
} else {
return null;
}
}
if ($class === '\SplFileObject') {
if (is_a($data, SplFileObject::class)) {
return $data;
}
$data = Psr7\Utils::streamFor($data);
/** @var Message\StreamInterface $data */
// determine file name
if (
is_array($httpHeaders)
&& array_key_exists('Content-Disposition', $httpHeaders)
&& preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)
) {
$filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]);
} else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), '');
}
$file = fopen($filename, 'w');
while ($chunk = $data->read(200)) {
fwrite($file, $chunk);
}
fclose($file);
return new \SplFileObject($filename, 'r');
}
/** @psalm-suppress ParadoxicalCondition */
if (in_array($class, [{{&primitives}}], true)) {
settype($data, $class);
return $data;
}
// handles unsupported union types like "bool|int|string"
if (!class_exists($class)) {
return $data;
}
if (method_exists($class, 'getAllowableEnumValues')) {
if (!in_array($data, $class::getAllowableEnumValues(), true)) {
$imploded = implode("', '", $class::getAllowableEnumValues());
throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'");
}
return $data;
} else {
$data = is_string($data) ? json_decode($data) : $data;
// If a discriminator is defined and points to a valid subclass, use it.
$discriminator = $class::DISCRIMINATOR;
$discriminatorValue = null;
if (is_object($data)) {
$discriminatorValue = $data->{$discriminator} ?? null;
} elseif (is_array($data)) {
$discriminatorValue = $data[$discriminator] ?? null;
}
$discrimnatorSubclassFound = false;
if (!empty($discriminator) && is_string($discriminatorValue)) {
$subclass = '\HelloSignSDK\Model\\' . $discriminatorValue;
if (is_subclass_of($subclass, $class)) {
$class = $subclass;
$discrimnatorSubclassFound = true;
}
}
if (
!$discrimnatorSubclassFound
&& !empty($discriminator)
&& method_exists($class, 'discriminatorClassName')
) {
$subclass = call_user_func(
"{$class}::discriminatorClassName",
(array) $data,
);
if (empty($subclass)) {
return null;
}
$class = $subclass;
$discrimnatorSubclassFound = true;
}
/** @var ModelInterface $instance */
$instance = new $class();
foreach ($instance::openAPITypes() as $property => $type) {
$propertySetter = $instance::setters()[$property];
if (!isset($propertySetter)) {
continue;
}
// Support object notation and array access
if (is_object($data) && isset($data->{$instance::attributeMap()[$property]})) {
$propertyValue = $data->{$instance::attributeMap()[$property]};
$instance->$propertySetter(self::deserialize($propertyValue, $type, null));
} elseif (is_array($data) && isset($data[$instance::attributeMap()[$property]])) {
$propertyValue = $data[$instance::attributeMap()[$property]];
$instance->$propertySetter(self::deserialize($propertyValue, $type, null));
}
}
return $instance;
}
}
/**
* Allows a multipart/form-data request to grab data from the typed
* class created by OpenAPI.
*/
public static function getFormParams(Model\ModelInterface $model): array
{
$apiTypes = $model::openAPITypes();
$formParams = [];
$hasFile = false;
$keyCount = [];
foreach ($model::attributeMap() as $key => $_) {
// form params
$value = $model->offsetGet($key);
if ($value === null) {
continue;
}
$true_key = $key;
if (strpos($apiTypes[$key], 'SplFileObject') !== false) {
$hasFile = true;
if (strpos($apiTypes[$key], 'SplFileObject[]') !== false) {
if (!array_key_exists($key, $keyCount)) {
$keyCount[$key] = 0;
}
foreach ($value as $file) {
$fileIndex = $keyCount[$key];
/**
* flat convert nested arrays into flat arrays, but making
* the literal [] a part of key value
*
* example: "file[0]={resource}"
*/
$true_key = "{$key}[{$fileIndex}]";
$keyCount[$key]++;
$formParams[$true_key] = Psr7\Utils::tryFopen(
ObjectSerializer::toFormValue($file),
'rb'
);
}
continue;
}
$formParams[$true_key] = Psr7\Utils::tryFopen(
ObjectSerializer::toFormValue($value),
'rb'
);
continue;
}
$formParams[$true_key] = is_scalar($value)
? ObjectSerializer::toFormValue($value)
: Utils::jsonEncode(
ObjectSerializer::sanitizeForSerialization(
$value
)
);
}
return $hasFile ? $formParams : [];
}
}