BaseDto.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. namespace UCore\Dto;
  3. use Illuminate\Contracts\Support\Arrayable;
  4. use Illuminate\Contracts\Support\Jsonable;
  5. use JsonSerializable;
  6. use Serializable;
  7. /**
  8. * DTO基类
  9. *
  10. * 为所有DTO提供基础功能,包括:
  11. * 1. 数组转换
  12. * 2. JSON序列化
  13. * 3. 从数组创建对象
  14. * 4. PHP序列化支持,便于缓存
  15. * 不要在构造函数定义属性
  16. */
  17. abstract class BaseDto implements Arrayable, JsonSerializable, Jsonable, Serializable
  18. {
  19. /**
  20. * 从数组创建DTO对象
  21. *
  22. * 子类可以覆盖此方法以提供自定义的创建逻辑
  23. *
  24. * @param array $data 数据数组
  25. * @return static
  26. */
  27. public static function fromArray(array $data): static
  28. {
  29. $dto = new static();
  30. foreach ($data as $key => $value) {
  31. // 转换下划线命名为驼峰命名
  32. $property = static::snakeToCamel($key);
  33. // 如果属性存在,则设置值
  34. if (property_exists($dto, $property)) {
  35. $dto->{$property} = $value;
  36. }
  37. }
  38. return $dto;
  39. }
  40. /**
  41. * 转换为数组
  42. *
  43. * 将DTO对象的所有公共属性转换为数组
  44. *
  45. * @return array
  46. */
  47. public function toArray(): array
  48. {
  49. $result = [];
  50. $reflection = new \ReflectionClass($this);
  51. $properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
  52. foreach ($properties as $property) {
  53. $name = $property->getName();
  54. $value = $this->{$name};
  55. // 转换驼峰命名为下划线命名
  56. $key = static::camelToSnake($name);
  57. // 处理嵌套的DTO对象或DTO数组
  58. if ($value instanceof Arrayable) {
  59. $result[$key] = $value->toArray();
  60. } elseif (is_array($value)) {
  61. $result[$key] = $this->processArrayValues($value);
  62. } else {
  63. $result[$key] = $value;
  64. }
  65. }
  66. return $result;
  67. }
  68. /**
  69. * 处理数组中的值
  70. *
  71. * 递归处理数组中的DTO对象
  72. *
  73. * @param array $array 要处理的数组
  74. * @return array 处理后的数组
  75. */
  76. protected function processArrayValues(array $array): array
  77. {
  78. $result = [];
  79. foreach ($array as $key => $value) {
  80. if ($value instanceof Arrayable) {
  81. $result[$key] = $value->toArray();
  82. } elseif (is_array($value)) {
  83. $result[$key] = $this->processArrayValues($value);
  84. } else {
  85. $result[$key] = $value;
  86. }
  87. }
  88. return $result;
  89. }
  90. /**
  91. * JSON序列化
  92. *
  93. * 实现JsonSerializable接口,使DTO对象可以直接被json_encode()处理
  94. *
  95. * @return array
  96. */
  97. public function jsonSerialize(): array
  98. {
  99. return $this->toArray();
  100. }
  101. /**
  102. * 转换为JSON字符串
  103. *
  104. * @param int $options JSON编码选项
  105. * @return string
  106. */
  107. public function toJson($options = 0): string
  108. {
  109. return json_encode($this->jsonSerialize(), $options);
  110. }
  111. /**
  112. * 将下划线命名转换为驼峰命名
  113. *
  114. * @param string $input 输入字符串
  115. * @return string 驼峰命名的字符串
  116. */
  117. public static function snakeToCamel(string $input): string
  118. {
  119. return lcfirst(str_replace('_', '', ucwords($input, '_')));
  120. }
  121. /**
  122. * 将驼峰命名转换为下划线命名
  123. *
  124. * @param string $input 输入字符串
  125. * @return string 下划线命名的字符串
  126. */
  127. protected static function camelToSnake(string $input): string
  128. {
  129. return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $input));
  130. }
  131. /**
  132. * 创建一个新的DTO实例
  133. *
  134. * @param array $data 初始数据
  135. * @return static
  136. */
  137. public static function make(array $data = []): static
  138. {
  139. return static::fromArray($data);
  140. }
  141. /**
  142. * 将多个数组转换为DTO对象数组
  143. *
  144. * @param array $items 数据数组的数组
  145. * @return array DTO对象数组
  146. */
  147. public static function collection(array $items): array
  148. {
  149. return array_map(function ($item) {
  150. if ($item instanceof static) {
  151. return $item;
  152. }
  153. return static::fromArray($item);
  154. }, $items);
  155. }
  156. /**
  157. * 从缓存中恢复对象数组
  158. *
  159. * 当从缓存中获取对象数组时,可能会得到序列化的对象或数组
  160. * 该方法确保返回的是正确类型的DTO对象数组
  161. *
  162. * @param mixed $cachedData 缓存的数据
  163. * @return array DTO对象数组
  164. */
  165. public static function fromCache($cachedData): array
  166. {
  167. if (is_null($cachedData)) {
  168. return [];
  169. }
  170. if (!is_array($cachedData)) {
  171. return [];
  172. }
  173. $result = [];
  174. foreach ($cachedData as $key => $item) {
  175. if ($item instanceof static) {
  176. $result[$key] = $item;
  177. } elseif (is_array($item)) {
  178. $result[$key] = static::fromArray($item);
  179. }
  180. }
  181. return $result;
  182. }
  183. /**
  184. * 序列化对象
  185. *
  186. * 实现Serializable接口,使对象可以被序列化存储
  187. *
  188. * @return string 序列化后的字符串
  189. */
  190. public function serialize(): string
  191. {
  192. return serialize($this->toArray());
  193. }
  194. /**
  195. * 反序列化对象
  196. *
  197. * 实现Serializable接口,从序列化字符串创建对象
  198. *
  199. * @param string $data 序列化的字符串
  200. * @return void
  201. */
  202. public function unserialize(string $data): void
  203. {
  204. $values = unserialize($data);
  205. foreach ($values as $key => $value) {
  206. // 转换下划线命名为驼峰命名
  207. $property = static::snakeToCamel($key);
  208. // 如果属性存在,则设置值
  209. if (property_exists($this, $property)) {
  210. $this->{$property} = $value;
  211. }
  212. }
  213. }
  214. /**
  215. * 从对象创建新实例
  216. *
  217. * 用于快速复制DTO对象
  218. *
  219. * @return static 新的DTO实例
  220. */
  221. public function clone(): static
  222. {
  223. return static::fromArray($this->toArray());
  224. }
  225. /**
  226. * 检查对象是否为空
  227. *
  228. * 如果所有属性都为默认值或空值,则认为对象为空
  229. *
  230. * @return bool 对象是否为空
  231. */
  232. public function isEmpty(): bool
  233. {
  234. $reflection = new \ReflectionClass($this);
  235. $properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
  236. foreach ($properties as $property) {
  237. $name = $property->getName();
  238. $value = $this->{$name};
  239. // 检查属性值是否为空
  240. if (is_string($value) && $value !== '') {
  241. return false;
  242. } elseif (is_numeric($value) && $value !== 0) {
  243. return false;
  244. } elseif (is_array($value) && !empty($value)) {
  245. return false;
  246. } elseif (is_object($value) && $value instanceof self && !$value->isEmpty()) {
  247. return false;
  248. } elseif (!is_null($value) && !is_string($value) && !is_numeric($value) && !is_array($value) && !is_object($value)) {
  249. return false;
  250. }
  251. }
  252. return true;
  253. }
  254. }