| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- <?php
- namespace App\Module\Fund\Dto;
- use App\Module\Fund\Models\FundCurrencyModel;
- /**
- * 币种数据传输对象
- *
- * 用于在服务层返回币种信息,避免直接暴露模型对象
- */
- class CurrencyDto
- {
- /**
- * @var int 币种ID
- */
- public int $id;
- /**
- * @var string 币种标识
- */
- public string $identification;
- /**
- * @var string 币种图标
- */
- public string $icon;
- /**
- * @var string 币种名称
- */
- public string $name;
- /**
- * @var string|null 额外数据
- */
- public ?string $data1;
- /**
- * @var int 创建时间
- */
- public int $createTime;
- /**
- * @var int 更新时间
- */
- public int $updateTime;
- /**
- * @var int 精度(小数位数)
- */
- public int $precision = 2;
- /**
- * 从模型创建DTO
- *
- * @param FundCurrencyModel $model 币种模型
- * @return self
- */
- public static function fromModel(FundCurrencyModel $model): self
- {
- $dto = new self();
- $dto->id = $model->id;
- $dto->identification = $model->identification;
- $dto->icon = $model->icon;
- $dto->name = $model->name;
- $dto->data1 = $model->data1;
- $dto->createTime = $model->create_time;
- $dto->updateTime = $model->update_time;
-
- // 从data1字段中获取精度信息
- if (!empty($model->data1)) {
- $data = json_decode($model->data1, true);
- if (isset($data['precision'])) {
- $dto->precision = (int)$data['precision'];
- }
- }
-
- return $dto;
- }
- /**
- * 转换为数组
- *
- * @return array
- */
- public function toArray(): array
- {
- return [
- 'id' => $this->id,
- 'identification' => $this->identification,
- 'icon' => $this->icon,
- 'name' => $this->name,
- 'data1' => $this->data1,
- 'create_time' => $this->createTime,
- 'update_time' => $this->updateTime,
- 'precision' => $this->precision,
- ];
- }
- /**
- * 格式化金额显示
- *
- * @param int $amount 金额(整数形式)
- * @return string 格式化后的金额
- */
- public function formatAmount(int $amount): string
- {
- $divisor = pow(10, $this->precision);
-
- // 将整数形式的金额转换为带小数的形式
- $formattedAmount = number_format($amount / $divisor, $this->precision, '.', ',');
-
- return $this->identification . ' ' . $formattedAmount;
- }
- /**
- * 将用户输入的金额转换为系统存储的整数形式
- *
- * @param float $amount 用户输入的金额
- * @return int 系统存储的整数形式金额
- */
- public function convertToStorageAmount(float $amount): int
- {
- $multiplier = pow(10, $this->precision);
-
- return (int)round($amount * $multiplier);
- }
- /**
- * 将系统存储的整数形式金额转换为实际金额
- *
- * @param int $storageAmount 系统存储的整数形式金额
- * @return float 实际金额
- */
- public function convertFromStorageAmount(int $storageAmount): float
- {
- $divisor = pow(10, $this->precision);
-
- return $storageAmount / $divisor;
- }
- }
|