FundAccountDto.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace App\Module\Fund\Dto;
  3. use App\Module\Fund\Enums\FUND_TYPE;
  4. use App\Module\Fund\Models\FundModel;
  5. /**
  6. * 资金账户数据传输对象
  7. *
  8. * 用于在服务层返回资金账户信息,避免直接暴露模型对象
  9. */
  10. class FundAccountDto
  11. {
  12. /**
  13. * @var int 账户ID
  14. */
  15. public int $id;
  16. /**
  17. * @var int 用户ID
  18. */
  19. public int $userId;
  20. /**
  21. * @var int|FUND_TYPE 资金类型ID
  22. */
  23. public $fundId;
  24. /**
  25. * @var float 余额(小数形式)
  26. */
  27. public float $balance;
  28. /**
  29. * @var int 更新时间
  30. */
  31. public int $updateTime;
  32. /**
  33. * @var int 创建时间
  34. */
  35. public int $createTime;
  36. /**
  37. * @var string|null 资金类型名称(可选)
  38. */
  39. public ?string $fundName = null;
  40. /**
  41. * 从模型创建DTO
  42. *
  43. * @param FundModel $model 账户模型
  44. * @param array $fundNames 资金类型名称映射(可选)
  45. * @return self
  46. */
  47. public static function fromModel(FundModel $model, array $fundNames = []): self
  48. {
  49. $dto = new self();
  50. $dto->id = $model->id;
  51. $dto->userId = $model->user_id;
  52. $dto->fundId = $model->fund_id;
  53. // 直接使用数据库中的小数值
  54. $dto->balance = (float)$model->balance;
  55. $dto->updateTime = $model->update_time;
  56. $dto->createTime = $model->create_time;
  57. // 如果提供了资金类型名称映射,则设置资金类型名称
  58. if (!empty($fundNames) && isset($fundNames[$model->fund_id instanceof FUND_TYPE ? $model->fund_id->value : $model->fund_id])) {
  59. $dto->fundName = $fundNames[$model->fund_id instanceof FUND_TYPE ? $model->fund_id->value : $model->fund_id];
  60. }
  61. return $dto;
  62. }
  63. /**
  64. * 获取资金类型ID的整数值
  65. *
  66. * @return int
  67. */
  68. public function getFundId(): int
  69. {
  70. if ($this->fundId instanceof FUND_TYPE) {
  71. return $this->fundId->value;
  72. }
  73. return (int)$this->fundId;
  74. }
  75. /**
  76. * 转换为数组
  77. *
  78. * @return array
  79. */
  80. public function toArray(): array
  81. {
  82. $result = [
  83. 'id' => $this->id,
  84. 'user_id' => $this->userId,
  85. 'fund_id' => $this->fundId instanceof FUND_TYPE ? $this->fundId->value : $this->fundId,
  86. 'balance' => $this->balance,
  87. 'update_time' => $this->updateTime,
  88. 'create_time' => $this->createTime,
  89. ];
  90. if ($this->fundName !== null) {
  91. $result['fund_name'] = $this->fundName;
  92. }
  93. return $result;
  94. }
  95. }