ObjectSerializer.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * ObjectSerializer
  4. * PHP version 7.4
  5. *
  6. * @category Class
  7. * @package Lakala\OpenAPISDK
  8. * @author lucongyu
  9. * @link https://o.lakala.com
  10. */
  11. namespace SixShop\Lakala\OpenAPISDK\V3;
  12. class ObjectSerializer
  13. {
  14. public static function sanitizeForSerialization($data)
  15. {
  16. if (is_array($data)) {
  17. foreach ($data as $property => $value) {
  18. $data[$property] = self::sanitizeForSerialization($value);
  19. }
  20. return $data;
  21. } elseif (is_object($data)) {
  22. $values = [];
  23. foreach (get_object_vars($data) as $property => $value) {
  24. $values[$property] = self::sanitizeForSerialization($value);
  25. }
  26. return $values;
  27. } else {
  28. return $data;
  29. }
  30. }
  31. public static function deserialize($data, $class, $headers = null)
  32. {
  33. if ($class === '\DateTime') {
  34. return new \DateTime($data);
  35. } elseif (in_array($class, ['bool', 'boolean', 'int', 'integer', 'float', 'double', 'string', 'array'])) {
  36. settype($data, $class);
  37. return $data;
  38. } else {
  39. $instance = new $class();
  40. foreach ($data as $property => $value) {
  41. $camelProp = str_replace(' ', '', ucwords(str_replace('_', ' ', $property)));
  42. $setter = 'set' . $camelProp;
  43. if (method_exists($instance, $setter)) {
  44. $instance->$setter($value);
  45. }
  46. }
  47. if ($headers && method_exists($instance, 'setHeaders')) {
  48. $instance->setHeaders($headers);
  49. }
  50. return $instance;
  51. }
  52. }
  53. # 此方法仅针对请求Model参数的对象json编码处理
  54. public static function jsonencode($value)
  55. {
  56. if ($value === null || is_string($value)) {
  57. return $value;
  58. }
  59. if (is_array($value)) {
  60. return json_encode($value, JSON_UNESCAPED_UNICODE);
  61. }
  62. if (method_exists($value, 'jsonSerialize')) {
  63. return json_encode($value->jsonSerialize(), JSON_UNESCAPED_UNICODE);
  64. }
  65. return json_encode($value, JSON_UNESCAPED_UNICODE);
  66. }
  67. }