| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- <?php
- namespace App\Module\User\Dto;
- use App\Module\User\Models\UserInfo;
- use App\Module\User\Unit\UserOInfo;
- /**
- * 用户订单信息数据传输对象
- *
- * 用于在服务层返回用户订单信息,避免直接暴露模型对象
- */
- class UserOInfoDto
- {
- /**
- * @var int 用户ID
- */
- public int $userId;
- /**
- * @var string|null 头像
- */
- public ?string $avatar;
- /**
- * @var int 状态
- */
- public int $status;
- /**
- * @var string|null 昵称
- */
- public ?string $nickName;
- /**
- * @var string|null 手机号
- */
- public ?string $phone;
- /**
- * @var int|null 商户ID
- */
- public ?int $merchantId;
- /**
- * 从 UserOInfo 对象创建 DTO
- *
- * @param UserOInfo $userOInfo 用户订单信息对象
- * @return self
- */
- public static function fromUserOInfo(UserOInfo $userOInfo): self
- {
- $dto = new self();
- $dto->userId = $userOInfo->user_id;
- $dto->avatar = $userOInfo->avatar;
- $dto->status = $userOInfo->status;
- $dto->nickName = $userOInfo->nick_name;
- $dto->phone = $userOInfo->phone ?? null;
- $dto->merchantId = isset($userOInfo->merchant_id) ? $userOInfo->merchant_id : null;
- return $dto;
- }
- /**
- * 从 UserInfo 模型创建 DTO
- *
- * @param UserInfo $userInfo 用户详细信息模型
- * @return self
- */
- public static function fromUserInfo(UserInfo $userInfo): self
- {
- $dto = new self();
- $dto->userId = $userInfo->user_id;
- $dto->avatar = $userInfo->avatar;
- $dto->status = $userInfo->status->value;
- $dto->nickName = $userInfo->nickname;
-
- // 如果模型已加载关联
- if ($userInfo->relationLoaded('user_phone') && $userInfo->user_phone) {
- $dto->phone = $userInfo->user_phone->phone;
- }
-
- // 如果模型已加载关联
- if ($userInfo->relationLoaded('merchant') && $userInfo->merchant) {
- $dto->merchantId = $userInfo->merchant->id;
- }
- return $dto;
- }
- /**
- * 创建已注销用户的 DTO
- *
- * @param int $userId 用户ID
- * @return self
- */
- public static function createDeleted(int $userId): self
- {
- $dto = new self();
- $dto->userId = $userId;
- $dto->avatar = '';
- $dto->status = 0;
- $dto->nickName = '已注销';
- $dto->phone = null;
- $dto->merchantId = null;
- return $dto;
- }
- /**
- * 转换为数组
- *
- * @return array
- */
- public function toArray(): array
- {
- $result = [
- 'user_id' => $this->userId,
- 'avatar' => $this->avatar,
- 'status' => $this->status,
- 'nick_name' => $this->nickName,
- ];
- if ($this->phone !== null) {
- $result['phone'] = $this->phone;
- }
- if ($this->merchantId !== null) {
- $result['merchant_id'] = $this->merchantId;
- }
- return $result;
- }
- }
|