github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/php/ObjectSerializer.mustache (about) 1 <?php 2 /** 3 * ObjectSerializer 4 * 5 * PHP version 5 6 * 7 * @category Class 8 * @package {{invokerPackage}} 9 * @author OpenAPI Generator team 10 * @link https://openapi-generator.tech 11 */ 12 13 {{>partial_header}} 14 /** 15 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). 16 * https://openapi-generator.tech 17 * Do not edit the class manually. 18 */ 19 20 namespace {{invokerPackage}}; 21 22 use {{modelPackage}}\ModelInterface; 23 24 /** 25 * ObjectSerializer Class Doc Comment 26 * 27 * @category Class 28 * @package {{invokerPackage}} 29 * @author OpenAPI Generator team 30 * @link https://openapi-generator.tech 31 */ 32 class ObjectSerializer 33 { 34 /** @var string */ 35 private static $dateTimeFormat = \DateTime::ATOM; 36 37 /** 38 * Change the date format 39 * 40 * @param string $format the new date format to use 41 */ 42 public static function setDateTimeFormat($format) 43 { 44 self::$dateTimeFormat = $format; 45 } 46 47 /** 48 * Serialize data 49 * 50 * @param mixed $data the data to serialize 51 * @param string $type the OpenAPIToolsType of the data 52 * @param string $format the format of the OpenAPITools type of the data 53 * 54 * @return string|object serialized form of $data 55 */ 56 public static function sanitizeForSerialization($data, $type = null, $format = null) 57 { 58 if (is_scalar($data) || null === $data) { 59 return $data; 60 } elseif ($data instanceof \DateTime) { 61 return ($format === 'date') ? $data->format('Y-m-d') : $data->format(self::$dateTimeFormat); 62 } elseif (is_array($data)) { 63 foreach ($data as $property => $value) { 64 $data[$property] = self::sanitizeForSerialization($value); 65 } 66 return $data; 67 } elseif (is_object($data)) { 68 $values = []; 69 if ($data instanceof ModelInterface) { 70 $formats = $data::openAPIFormats(); 71 foreach ($data::openAPITypes() as $property => $openAPIType) { 72 $getter = $data::getters()[$property]; 73 $value = $data->$getter(); 74 if ($value !== null 75 && !in_array($openAPIType, [{{&primitives}}], true) 76 && method_exists($openAPIType, 'getAllowableEnumValues') 77 && !in_array($value, $openAPIType::getAllowableEnumValues(), true)) { 78 $imploded = implode("', '", $openAPIType::getAllowableEnumValues()); 79 throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'"); 80 } 81 if ($value !== null) { 82 $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]); 83 } 84 } 85 } else { 86 foreach($data as $property => $value) { 87 $values[$property] = self::sanitizeForSerialization($value); 88 } 89 } 90 return (object)$values; 91 } else { 92 return (string)$data; 93 } 94 } 95 96 /** 97 * Sanitize filename by removing path. 98 * e.g. ../../sun.gif becomes sun.gif 99 * 100 * @param string $filename filename to be sanitized 101 * 102 * @return string the sanitized filename 103 */ 104 public static function sanitizeFilename($filename) 105 { 106 if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { 107 return $match[1]; 108 } else { 109 return $filename; 110 } 111 } 112 113 /** 114 * Take value and turn it into a string suitable for inclusion in 115 * the path, by url-encoding. 116 * 117 * @param string $value a string which will be part of the path 118 * 119 * @return string the serialized object 120 */ 121 public static function toPathValue($value) 122 { 123 return rawurlencode(self::toString($value)); 124 } 125 126 /** 127 * Take value and turn it into a string suitable for inclusion in 128 * the query, by imploding comma-separated if it's an object. 129 * If it's a string, pass through unchanged. It will be url-encoded 130 * later. 131 * 132 * @param string[]|string|\DateTime $object an object to be serialized to a string 133 * 134 * @return string the serialized object 135 */ 136 public static function toQueryValue($object) 137 { 138 if (is_array($object)) { 139 return implode(',', $object); 140 } else { 141 return self::toString($object); 142 } 143 } 144 145 /** 146 * Take value and turn it into a string suitable for inclusion in 147 * the header. If it's a string, pass through unchanged 148 * If it's a datetime object, format it in ISO8601 149 * 150 * @param string $value a string which will be part of the header 151 * 152 * @return string the header string 153 */ 154 public static function toHeaderValue($value) 155 { 156 if (method_exists($value, 'toHeaderValue')) { 157 return $value->toHeaderValue(); 158 } 159 160 return self::toString($value); 161 } 162 163 /** 164 * Take value and turn it into a string suitable for inclusion in 165 * the http body (form parameter). If it's a string, pass through unchanged 166 * If it's a datetime object, format it in ISO8601 167 * 168 * @param string|\SplFileObject $value the value of the form parameter 169 * 170 * @return string the form string 171 */ 172 public static function toFormValue($value) 173 { 174 if ($value instanceof \SplFileObject) { 175 return $value->getRealPath(); 176 } else { 177 return self::toString($value); 178 } 179 } 180 181 /** 182 * Take value and turn it into a string suitable for inclusion in 183 * the parameter. If it's a string, pass through unchanged 184 * If it's a datetime object, format it in ISO8601 185 * If it's a boolean, convert it to "true" or "false". 186 * 187 * @param string|bool|\DateTime $value the value of the parameter 188 * 189 * @return string the header string 190 */ 191 public static function toString($value) 192 { 193 if ($value instanceof \DateTime) { // datetime in ISO8601 format 194 return $value->format(self::$dateTimeFormat); 195 } else if (is_bool($value)) { 196 return $value ? 'true' : 'false'; 197 } else { 198 return $value; 199 } 200 } 201 202 /** 203 * Serialize an array to a string. 204 * 205 * @param array $collection collection to serialize to a string 206 * @param string $style the format use for serialization (csv, 207 * ssv, tsv, pipes, multi) 208 * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array 209 * 210 * @return string 211 */ 212 public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false) 213 { 214 if ($allowCollectionFormatMulti && ('multi' === $style)) { 215 // http_build_query() almost does the job for us. We just 216 // need to fix the result of multidimensional arrays. 217 return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); 218 } 219 switch ($style) { 220 case 'pipeDelimited': 221 case 'pipes': 222 return implode('|', $collection); 223 224 case 'tsv': 225 return implode("\t", $collection); 226 227 case 'spaceDelimited': 228 case 'ssv': 229 return implode(' ', $collection); 230 231 case 'simple': 232 case 'csv': 233 // Deliberate fall through. CSV is default format. 234 default: 235 return implode(',', $collection); 236 } 237 } 238 239 /** 240 * Deserialize a JSON string into an object 241 * 242 * @param mixed $data object or primitive to be deserialized 243 * @param string $class class name is passed as a string 244 * @param string[] $httpHeaders HTTP headers 245 * @param string $discriminator discriminator if polymorphism is used 246 * 247 * @return object|array|null a single or an array of $class instances 248 */ 249 public static function deserialize($data, $class, $httpHeaders = null) 250 { 251 if (null === $data) { 252 return null; 253 } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] 254 $data = is_string($data) ? json_decode($data) : $data; 255 settype($data, 'array'); 256 $inner = substr($class, 4, -1); 257 $deserialized = []; 258 if (strrpos($inner, ",") !== false) { 259 $subClass_array = explode(',', $inner, 2); 260 $subClass = $subClass_array[1]; 261 foreach ($data as $key => $value) { 262 $deserialized[$key] = self::deserialize($value, $subClass, null); 263 } 264 } 265 return $deserialized; 266 } elseif (strcasecmp(substr($class, -2), '[]') === 0) { 267 $data = is_string($data) ? json_decode($data) : $data; 268 $subClass = substr($class, 0, -2); 269 $values = []; 270 foreach ($data as $key => $value) { 271 $values[] = self::deserialize($value, $subClass, null); 272 } 273 return $values; 274 } elseif ($class === 'object' || $class === 'array<string,string>') { 275 settype($data, 'array'); 276 return $data; 277 } elseif ($class === '\DateTime') { 278 // Some API's return an invalid, empty string as a 279 // date-time property. DateTime::__construct() will return 280 // the current time for empty input which is probably not 281 // what is meant. The invalid empty string is probably to 282 // be interpreted as a missing field/value. Let's handle 283 // this graceful. 284 if (!empty($data)) { 285 return new \DateTime($data); 286 } else { 287 return null; 288 } 289 } elseif ($class === '\SplFileObject') { 290 /** @var \Psr\Http\Message\StreamInterface $data */ 291 292 // determine file name 293 if (array_key_exists('Content-Disposition', $httpHeaders) && 294 preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { 295 $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); 296 } else { 297 $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); 298 } 299 300 $file = fopen($filename, 'w'); 301 while ($chunk = $data->read(200)) { 302 fwrite($file, $chunk); 303 } 304 fclose($file); 305 306 return new \SplFileObject($filename, 'r'); 307 } elseif (in_array($class, [{{&primitives}}], true)) { 308 settype($data, $class); 309 return $data; 310 } elseif (method_exists($class, 'getAllowableEnumValues')) { 311 if (!in_array($data, $class::getAllowableEnumValues(), true)) { 312 $imploded = implode("', '", $class::getAllowableEnumValues()); 313 throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); 314 } 315 return $data; 316 } else { 317 $data = is_string($data) ? json_decode($data) : $data; 318 // If a discriminator is defined and points to a valid subclass, use it. 319 $discriminator = $class::DISCRIMINATOR; 320 if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { 321 $subclass = '\{{invokerPackage}}\Model\\' . $data->{$discriminator}; 322 if (is_subclass_of($subclass, $class)) { 323 $class = $subclass; 324 } 325 } 326 $instance = new $class(); 327 foreach ($instance::openAPITypes() as $property => $type) { 328 $propertySetter = $instance::setters()[$property]; 329 330 if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { 331 continue; 332 } 333 334 $propertyValue = $data->{$instance::attributeMap()[$property]}; 335 if (isset($propertyValue)) { 336 $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); 337 } 338 } 339 return $instance; 340 } 341 } 342 }