UserInfoDto.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Module\User\Dto;
  3. use App\Module\User\Enums\STATUS;
  4. use App\Module\User\Models\UserInfo;
  5. /**
  6. * 用户详细信息数据传输对象
  7. *
  8. * 用于在服务层返回用户详细信息,避免直接暴露模型对象
  9. */
  10. class UserInfoDto
  11. {
  12. /**
  13. * @var int 用户ID
  14. */
  15. public int $userId;
  16. /**
  17. * @var STATUS 状态
  18. */
  19. public STATUS $status;
  20. /**
  21. * @var string|null Google 2FA 密钥
  22. */
  23. public ?string $google2faSecret;
  24. /**
  25. * @var string|null 昵称
  26. */
  27. public ?string $nickname;
  28. /**
  29. * @var string|null 头像
  30. */
  31. public ?string $avatar;
  32. /**
  33. * @var string|null 微信ID
  34. */
  35. public ?string $wxId;
  36. /**
  37. * @var string 创建时间
  38. */
  39. public string $createdAt;
  40. /**
  41. * @var string 更新时间
  42. */
  43. public string $updatedAt;
  44. /**
  45. * @var UserPhoneDto|null 用户手机信息
  46. */
  47. public ?UserPhoneDto $phone = null;
  48. /**
  49. * 从模型创建DTO
  50. *
  51. * @param UserInfo $model 用户详细信息模型
  52. * @param bool $withPhone 是否包含用户手机信息
  53. * @return self
  54. */
  55. public static function fromModel(UserInfo $model, bool $withPhone = false): self
  56. {
  57. $dto = new self();
  58. $dto->userId = $model->user_id;
  59. $dto->status = $model->status;
  60. $dto->google2faSecret = $model->google2fa_secret;
  61. $dto->nickname = $model->nickname;
  62. $dto->avatar = $model->avatar;
  63. $dto->wxId = $model->wx_id;
  64. $dto->createdAt = $model->created_at ? $model->created_at->toDateTimeString() : '';
  65. $dto->updatedAt = $model->updated_at ? $model->updated_at->toDateTimeString() : '';
  66. // 如果需要包含用户手机信息,并且模型已加载关联
  67. if ($withPhone && $model->relationLoaded('user_phone') && $model->user_phone) {
  68. $dto->phone = UserPhoneDto::fromModel($model->user_phone);
  69. }
  70. return $dto;
  71. }
  72. /**
  73. * 转换为数组
  74. *
  75. * @return array
  76. */
  77. public function toArray(): array
  78. {
  79. $result = [
  80. 'user_id' => $this->userId,
  81. 'status' => $this->status->value,
  82. 'status_name' => $this->status->name,
  83. 'google2fa_secret' => $this->google2faSecret,
  84. 'nickname' => $this->nickname,
  85. 'avatar' => $this->avatar,
  86. 'wx_id' => $this->wxId,
  87. 'created_at' => $this->createdAt,
  88. 'updated_at' => $this->updatedAt,
  89. ];
  90. if ($this->phone !== null) {
  91. $result['phone'] = $this->phone->toArray();
  92. }
  93. return $result;
  94. }
  95. }