1: <?php
2: /**
3: * ObjectSerializer
4: *
5: * PHP version 7.4
6: *
7: * @category Class
8: * @package Ally\PetStore
9: * @author OpenAPI Generator team
10: * @link https://openapi-generator.tech
11: */
12:
13: /**
14: * OpenAPI Petstore
15: *
16: * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
17: *
18: * The version of the OpenAPI document: 1.0.0
19: * Generated by: https://openapi-generator.tech
20: * OpenAPI Generator version: 6.1.0-SNAPSHOT
21: */
22:
23: /**
24: * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
25: * https://openapi-generator.tech
26: * Do not edit the class manually.
27: */
28:
29: namespace Ally\PetStore;
30:
31: use GuzzleHttp\Psr7\Utils;
32: use Ally\PetStore\Schema\ModelInterface;
33:
34: /**
35: * ObjectSerializer Class Doc Comment
36: *
37: * @category Class
38: * @package Ally\PetStore
39: * @author OpenAPI Generator team
40: * @link https://openapi-generator.tech
41: */
42: class ObjectSerializer
43: {
44: /** @var string */
45: private static $dateTimeFormat = \DateTime::ATOM;
46:
47: /**
48: * Change the date format
49: *
50: * @param string $format the new date format to use
51: */
52: public static function setDateTimeFormat($format)
53: {
54: self::$dateTimeFormat = $format;
55: }
56:
57: /**
58: * Serialize data
59: *
60: * @param mixed $data the data to serialize
61: * @param string $type the OpenAPIToolsType of the data
62: * @param string $format the format of the OpenAPITools type of the data
63: *
64: * @return scalar|object|array|null serialized form of $data
65: */
66: public static function sanitizeForSerialization($data, $type = null, $format = null)
67: {
68: if (is_scalar($data) || null === $data) {
69: return $data;
70: }
71:
72: if ($data instanceof \DateTime) {
73: return ($format === 'date') ? $data->format('Y-m-d') : $data->format(self::$dateTimeFormat);
74: }
75:
76: if (is_array($data)) {
77: foreach ($data as $property => $value) {
78: $data[$property] = self::sanitizeForSerialization($value);
79: }
80: return $data;
81: }
82:
83: if (is_object($data)) {
84: $values = [];
85: if ($data instanceof ModelInterface) {
86: $formats = $data::openAPIFormats();
87: foreach ($data::openAPITypes() as $property => $openAPIType) {
88: $getter = $data::getters()[$property];
89: $value = $data->$getter();
90: if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) {
91: $callable = [$openAPIType, 'getAllowableEnumValues'];
92: if (is_callable($callable)) {
93: /** array $callable */
94: $allowedEnumTypes = $callable();
95: if (!in_array($value, $allowedEnumTypes, true)) {
96: $imploded = implode("', '", $allowedEnumTypes);
97: throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'");
98: }
99: }
100: }
101: if (($data::isNullable($property) && $data->isNullableSetToNull($property)) || $value !== null) {
102: $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]);
103: }
104: }
105: } else {
106: foreach($data as $property => $value) {
107: $values[$property] = self::sanitizeForSerialization($value);
108: }
109: }
110: return (object)$values;
111: } else {
112: return (string)$data;
113: }
114: }
115:
116: /**
117: * Sanitize filename by removing path.
118: * e.g. ../../sun.gif becomes sun.gif
119: *
120: * @param string $filename filename to be sanitized
121: *
122: * @return string the sanitized filename
123: */
124: public static function sanitizeFilename($filename)
125: {
126: if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) {
127: return $match[1];
128: } else {
129: return $filename;
130: }
131: }
132:
133: /**
134: * Shorter timestamp microseconds to 6 digits length.
135: *
136: * @param string $timestamp Original timestamp
137: *
138: * @return string the shorten timestamp
139: */
140: public static function sanitizeTimestamp($timestamp)
141: {
142: if (!is_string($timestamp)) return $timestamp;
143:
144: return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp);
145: }
146:
147: /**
148: * Take value and turn it into a string suitable for inclusion in
149: * the path, by url-encoding.
150: *
151: * @param string $value a string which will be part of the path
152: *
153: * @return string the serialized object
154: */
155: public static function toPathValue($value)
156: {
157: return rawurlencode(self::toString($value));
158: }
159:
160: /**
161: * Take query parameter properties and turn it into an array suitable for
162: * native http_build_query or GuzzleHttp\Psr7\Query::build.
163: *
164: * @param mixed $value Parameter value
165: * @param string $paramName Parameter name
166: * @param string $openApiType OpenAPIType eg. array or object
167: * @param string $style Parameter serialization style
168: * @param bool $explode Parameter explode option
169: * @param bool $required Whether query param is required or not
170: *
171: * @return array
172: */
173: public static function toQueryValue(
174: $value,
175: string $paramName,
176: string $openApiType = 'string',
177: string $style = 'form',
178: bool $explode = true,
179: bool $required = true
180: ): array {
181: if (
182: empty($value)
183: && ($value !== false || $openApiType !== 'boolean') // if $value === false and $openApiType ==='boolean' it isn't empty
184: ) {
185: if ($required) {
186: return ["{$paramName}" => ''];
187: } else {
188: return [];
189: }
190: }
191:
192: $query = [];
193: $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value;
194:
195: // since \GuzzleHttp\Psr7\Query::build fails with nested arrays
196: // need to flatten array first
197: $flattenArray = function ($arr, $name, &$result = []) use (&$flattenArray, $style, $explode) {
198: if (!is_array($arr)) return $arr;
199:
200: foreach ($arr as $k => $v) {
201: $prop = ($style === 'deepObject') ? $prop = "{$name}[{$k}]" : $k;
202:
203: if (is_array($v)) {
204: $flattenArray($v, $prop, $result);
205: } else {
206: if ($style !== 'deepObject' && !$explode) {
207: // push key itself
208: $result[] = $prop;
209: }
210: $result[$prop] = $v;
211: }
212: }
213: return $result;
214: };
215:
216: $value = $flattenArray($value, $paramName);
217:
218: if ($openApiType === 'object' && ($style === 'deepObject' || $explode)) {
219: return $value;
220: }
221:
222: if ('boolean' === $openApiType && is_bool($value)) {
223: $value = self::convertBoolToQueryStringFormat($value);
224: }
225:
226: // handle style in serializeCollection
227: $query[$paramName] = ($explode) ? $value : self::serializeCollection((array)$value, $style);
228:
229: return $query;
230: }
231:
232: /**
233: * Convert boolean value to format for query string.
234: *
235: * @param bool $value Boolean value
236: *
237: * @return int|string Boolean value in format
238: */
239: public static function convertBoolToQueryStringFormat(bool $value)
240: {
241: if (Configuration::BOOLEAN_FORMAT_STRING == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString()) {
242: return $value ? 'true' : 'false';
243: }
244:
245: return (int) $value;
246: }
247:
248: /**
249: * Take value and turn it into a string suitable for inclusion in
250: * the header. If it's a string, pass through unchanged
251: * If it's a datetime object, format it in ISO8601
252: *
253: * @param string $value a string which will be part of the header
254: *
255: * @return string the header string
256: */
257: public static function toHeaderValue($value)
258: {
259: $callable = [$value, 'toHeaderValue'];
260: if (is_callable($callable)) {
261: return $callable();
262: }
263:
264: return self::toString($value);
265: }
266:
267: /**
268: * Take value and turn it into a string suitable for inclusion in
269: * the http body (form parameter). If it's a string, pass through unchanged
270: * If it's a datetime object, format it in ISO8601
271: *
272: * @param string|\SplFileObject $value the value of the form parameter
273: *
274: * @return string the form string
275: */
276: public static function toFormValue($value)
277: {
278: if ($value instanceof \SplFileObject) {
279: return $value->getRealPath();
280: } else {
281: return self::toString($value);
282: }
283: }
284:
285: /**
286: * Take value and turn it into a string suitable for inclusion in
287: * the parameter. If it's a string, pass through unchanged
288: * If it's a datetime object, format it in ISO8601
289: * If it's a boolean, convert it to "true" or "false".
290: *
291: * @param string|bool|\DateTime $value the value of the parameter
292: *
293: * @return string the header string
294: */
295: public static function toString($value)
296: {
297: if ($value instanceof \DateTime) { // datetime in ISO8601 format
298: return $value->format(self::$dateTimeFormat);
299: } elseif (is_bool($value)) {
300: return $value ? 'true' : 'false';
301: } else {
302: return (string) $value;
303: }
304: }
305:
306: /**
307: * Serialize an array to a string.
308: *
309: * @param array $collection collection to serialize to a string
310: * @param string $style the format use for serialization (csv,
311: * ssv, tsv, pipes, multi)
312: * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array
313: *
314: * @return string
315: */
316: public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false)
317: {
318: if ($allowCollectionFormatMulti && ('multi' === $style)) {
319: // http_build_query() almost does the job for us. We just
320: // need to fix the result of multidimensional arrays.
321: return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&'));
322: }
323: switch ($style) {
324: case 'pipeDelimited':
325: case 'pipes':
326: return implode('|', $collection);
327:
328: case 'tsv':
329: return implode("\t", $collection);
330:
331: case 'spaceDelimited':
332: case 'ssv':
333: return implode(' ', $collection);
334:
335: case 'simple':
336: case 'csv':
337: // Deliberate fall through. CSV is default format.
338: default:
339: return implode(',', $collection);
340: }
341: }
342:
343: /**
344: * Deserialize a JSON string into an object
345: *
346: * @param mixed $data object or primitive to be deserialized
347: * @param string $class class name is passed as a string
348: * @param string[] $httpHeaders HTTP headers
349: * @param string $discriminator discriminator if polymorphism is used
350: *
351: * @return object|array|null a single or an array of $class instances
352: */
353: public static function deserialize($data, $class, $httpHeaders = null)
354: {
355: if (null === $data) {
356: return null;
357: }
358:
359: if (strcasecmp(substr($class, -2), '[]') === 0) {
360: $data = is_string($data) ? json_decode($data) : $data;
361:
362: if (!is_array($data)) {
363: throw new \InvalidArgumentException("Invalid array '$class'");
364: }
365:
366: $subClass = substr($class, 0, -2);
367: $values = [];
368: foreach ($data as $key => $value) {
369: $values[] = self::deserialize($value, $subClass, null);
370: }
371: return $values;
372: }
373:
374: if (preg_match('/^(array<|map\[)/', $class)) { // for associative array e.g. array<string,int>
375: $data = is_string($data) ? json_decode($data) : $data;
376: settype($data, 'array');
377: $inner = substr($class, 4, -1);
378: $deserialized = [];
379: if (strrpos($inner, ",") !== false) {
380: $subClass_array = explode(',', $inner, 2);
381: $subClass = $subClass_array[1];
382: foreach ($data as $key => $value) {
383: $deserialized[$key] = self::deserialize($value, $subClass, null);
384: }
385: }
386: return $deserialized;
387: }
388:
389: if ($class === 'object') {
390: settype($data, 'array');
391: return $data;
392: } elseif ($class === 'mixed') {
393: settype($data, gettype($data));
394: return $data;
395: }
396:
397: if ($class === '\DateTime') {
398: // Some API's return an invalid, empty string as a
399: // date-time property. DateTime::__construct() will return
400: // the current time for empty input which is probably not
401: // what is meant. The invalid empty string is probably to
402: // be interpreted as a missing field/value. Let's handle
403: // this graceful.
404: if (!empty($data)) {
405: try {
406: return new \DateTime($data);
407: } catch (\Exception $exception) {
408: // Some API's return a date-time with too high nanosecond
409: // precision for php's DateTime to handle.
410: // With provided regexp 6 digits of microseconds saved
411: return new \DateTime(self::sanitizeTimestamp($data));
412: }
413: } else {
414: return null;
415: }
416: }
417:
418: if ($class === '\SplFileObject') {
419: $data = Utils::streamFor($data);
420:
421: /** @var \Psr\Http\Message\StreamInterface $data */
422:
423: // determine file name
424: if (
425: is_array($httpHeaders)
426: && array_key_exists('Content-Disposition', $httpHeaders)
427: && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)
428: ) {
429: $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]);
430: } else {
431: $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), '');
432: }
433:
434: $file = fopen($filename, 'w');
435: while ($chunk = $data->read(200)) {
436: fwrite($file, $chunk);
437: }
438: fclose($file);
439:
440: return new \SplFileObject($filename, 'r');
441: }
442:
443: /** @psalm-suppress ParadoxicalCondition */
444: if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) {
445: settype($data, $class);
446: return $data;
447: }
448:
449:
450: if (method_exists($class, 'getAllowableEnumValues')) {
451: if (!in_array($data, $class::getAllowableEnumValues(), true)) {
452: $imploded = implode("', '", $class::getAllowableEnumValues());
453: throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'");
454: }
455: return $data;
456: } else {
457: $data = is_string($data) ? json_decode($data) : $data;
458:
459: if (is_array($data)) {
460: $data = (object)$data;
461: }
462:
463: // If a discriminator is defined and points to a valid subclass, use it.
464: $discriminator = $class::DISCRIMINATOR;
465: if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) {
466: $subclass = '\Ally\PetStore\Model\\' . $data->{$discriminator};
467: if (is_subclass_of($subclass, $class)) {
468: $class = $subclass;
469: }
470: }
471:
472: /** @var ModelInterface $instance */
473: $instance = new $class();
474: foreach ($instance::openAPITypes() as $property => $type) {
475: $propertySetter = $instance::setters()[$property];
476:
477: if (!isset($propertySetter)) {
478: continue;
479: }
480:
481: if (!isset($data->{$instance::attributeMap()[$property]})) {
482: if ($instance::isNullable($property)) {
483: $instance->$propertySetter(null);
484: }
485:
486: continue;
487: }
488:
489: if (isset($data->{$instance::attributeMap()[$property]})) {
490: $propertyValue = $data->{$instance::attributeMap()[$property]};
491: $instance->$propertySetter(self::deserialize($propertyValue, $type, null));
492: }
493: }
494: return $instance;
495: }
496: }
497:
498: /**
499: * Native `http_build_query` wrapper.
500: * @see https://www.php.net/manual/en/function.http-build-query
501: *
502: * @param array|object $data May be an array or object containing properties.
503: * @param string $numeric_prefix If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.
504: * @param string|null $arg_separator arg_separator.output is used to separate arguments but may be overridden by specifying this parameter.
505: * @param int $encoding_type Encoding type. By default, PHP_QUERY_RFC1738.
506: *
507: * @return string
508: */
509: public static function buildQuery(
510: $data,
511: string $numeric_prefix = '',
512: ?string $arg_separator = null,
513: int $encoding_type = \PHP_QUERY_RFC3986
514: ): string {
515: return \GuzzleHttp\Psr7\Query::build($data, $encoding_type);
516: }
517: }
518: