| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace App\Module\User\Dto;
- use App\Module\User\Enums\STATUS;
- use App\Module\User\Models\UserInfo;
- /**
- * 用户详细信息数据传输对象
- *
- * 用于在服务层返回用户详细信息,避免直接暴露模型对象
- */
- class UserInfoDto
- {
- /**
- * @var int 用户ID
- */
- public int $userId;
- /**
- * @var STATUS 状态
- */
- public STATUS $status;
- /**
- * @var string|null Google 2FA 密钥
- */
- public ?string $google2faSecret;
- /**
- * @var string|null 昵称
- */
- public ?string $nickname;
- /**
- * @var string|null 头像
- */
- public ?string $avatar;
- /**
- * @var string|null 微信ID
- */
- public ?string $wxId;
- /**
- * @var string 创建时间
- */
- public string $createdAt;
- /**
- * @var string 更新时间
- */
- public string $updatedAt;
- /**
- * @var UserPhoneDto|null 用户手机信息
- */
- public ?UserPhoneDto $phone = null;
- /**
- * 从模型创建DTO
- *
- * @param UserInfo $model 用户详细信息模型
- * @param bool $withPhone 是否包含用户手机信息
- * @return self
- */
- public static function fromModel(UserInfo $model, bool $withPhone = false): self
- {
- $dto = new self();
- $dto->userId = $model->user_id;
- $dto->status = $model->status;
- $dto->google2faSecret = $model->google2fa_secret;
- $dto->nickname = $model->nickname;
- $dto->avatar = $model->avatar;
- $dto->wxId = $model->wx_id;
- $dto->createdAt = $model->created_at ? $model->created_at->toDateTimeString() : '';
- $dto->updatedAt = $model->updated_at ? $model->updated_at->toDateTimeString() : '';
- // 如果需要包含用户手机信息,并且模型已加载关联
- if ($withPhone && $model->relationLoaded('user_phone') && $model->user_phone) {
- $dto->phone = UserPhoneDto::fromModel($model->user_phone);
- }
- return $dto;
- }
- /**
- * 转换为数组
- *
- * @return array
- */
- public function toArray(): array
- {
- $result = [
- 'user_id' => $this->userId,
- 'status' => $this->status->value,
- 'status_name' => $this->status->name,
- 'google2fa_secret' => $this->google2faSecret,
- 'nickname' => $this->nickname,
- 'avatar' => $this->avatar,
- 'wx_id' => $this->wxId,
- 'created_at' => $this->createdAt,
- 'updated_at' => $this->updatedAt,
- ];
- if ($this->phone !== null) {
- $result['phone'] = $this->phone->toArray();
- }
- return $result;
- }
- }
|