AbstractModel.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace addons\QiShangTong\common\expand\sdk\qishangtong;
  3. /**
  4. * @property string $app_key
  5. * @property string $sign
  6. * @property int $timestamp
  7. */
  8. abstract class AbstractModel
  9. {
  10. protected $error_message_map = [];
  11. private $common_error_message_map = [
  12. -1 => '系统异常',
  13. 9401020 => '参数有误'
  14. ];
  15. protected $data = [];
  16. public function __set($name, $value)
  17. {
  18. $this->data[$name] = $value;
  19. }
  20. public function __get($name)
  21. {
  22. return $this->data[$name] ?? null;
  23. }
  24. public function __isset($name)
  25. {
  26. return !empty($this->data[$name]);
  27. }
  28. /**
  29. * @return array
  30. */
  31. public function toArray()
  32. {
  33. $data = [];
  34. foreach ($this->data as $key => $value) {
  35. if ($value instanceof AbstractModel) {
  36. $data[$key] = $value->toArray();
  37. } else {
  38. if (is_array($value)) {
  39. foreach ($value as $k => $v) {
  40. if ($v instanceof AbstractModel) {
  41. if (!empty($v->toArray())) $data[$key][$k] = $v->toArray();
  42. } else {
  43. if (is_array($v)) {
  44. if (!empty($v)) $data[$key][$k] = $v;
  45. } elseif ($v !== '') $data[$key][$k] = $v;
  46. }
  47. }
  48. } else {
  49. if (is_array($value)) {
  50. if (!empty($value)) $data[$key] = $value;
  51. } elseif ($value !== '') $data[$key] = $value;
  52. }
  53. }
  54. }
  55. return $data;
  56. }
  57. /**
  58. * @param int $code
  59. * @return string|null
  60. */
  61. public function getError(int $code)
  62. {
  63. $error_map = array_merge($this->error_message_map, $this->common_error_message_map);
  64. return $error_map[$code] ?? null;
  65. }
  66. /**
  67. * @param array $data
  68. * @return string
  69. */
  70. public function valid(array $data): string
  71. {
  72. if (!isset($data['errcode'])) return '未知错误';
  73. if ($data['errcode'] != 0) {
  74. $err = $this->getError($data['errcode']);
  75. if ($err === null) return $data['errmsg'];
  76. return $err;
  77. }
  78. return '';
  79. }
  80. }