| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <?php
- namespace App\Module\Fund\Dto;
- use App\Module\Fund\Enums\FUND_TYPE;
- use App\Module\Fund\Models\FundModel;
- /**
- * 资金账户数据传输对象
- *
- * 用于在服务层返回资金账户信息,避免直接暴露模型对象
- */
- class FundAccountDto
- {
- /**
- * @var int 账户ID
- */
- public int $id;
- /**
- * @var int 用户ID
- */
- public int $userId;
- /**
- * @var int|FUND_TYPE 资金类型ID
- */
- public $fundId;
- /**
- * @var float 余额(小数形式)
- */
- public float $balance;
- /**
- * @var int 更新时间
- */
- public int $updateTime;
- /**
- * @var int 创建时间
- */
- public int $createTime;
- /**
- * @var string|null 资金类型名称(可选)
- */
- public ?string $fundName = null;
- /**
- * 从模型创建DTO
- *
- * @param FundModel $model 账户模型
- * @param array $fundNames 资金类型名称映射(可选)
- * @return self
- */
- public static function fromModel(FundModel $model, array $fundNames = []): self
- {
- $dto = new self();
- $dto->id = $model->id;
- $dto->userId = $model->user_id;
- $dto->fundId = $model->fund_id;
- // 直接使用数据库中的小数值
- $dto->balance = (float)$model->balance;
- $dto->updateTime = $model->update_time;
- $dto->createTime = $model->create_time;
- // 如果提供了资金类型名称映射,则设置资金类型名称
- if (!empty($fundNames) && isset($fundNames[$model->fund_id instanceof FUND_TYPE ? $model->fund_id->value : $model->fund_id])) {
- $dto->fundName = $fundNames[$model->fund_id instanceof FUND_TYPE ? $model->fund_id->value : $model->fund_id];
- }
- return $dto;
- }
- /**
- * 获取资金类型ID的整数值
- *
- * @return int
- */
- public function getFundId(): int
- {
- if ($this->fundId instanceof FUND_TYPE) {
- return $this->fundId->value;
- }
- return (int)$this->fundId;
- }
- /**
- * 转换为数组
- *
- * @return array
- */
- public function toArray(): array
- {
- $result = [
- 'id' => $this->id,
- 'user_id' => $this->userId,
- 'fund_id' => $this->fundId instanceof FUND_TYPE ? $this->fundId->value : $this->fundId,
- 'balance' => $this->balance,
- 'update_time' => $this->updateTime,
- 'create_time' => $this->createTime,
- ];
- if ($this->fundName !== null) {
- $result['fund_name'] = $this->fundName;
- }
- return $result;
- }
- }
|