ObjectSerializer.php 21 KB

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