AccountDto.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 AccountDto
  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 int 余额
  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. $dto->balance = $model->balance;
  54. $dto->updateTime = $model->update_time;
  55. $dto->createTime = $model->create_time;
  56. // 如果提供了资金类型名称映射,则设置资金类型名称
  57. if (!empty($fundNames) && isset($fundNames[$model->fund_id instanceof FUND_TYPE ? $model->fund_id->value : $model->fund_id])) {
  58. $dto->fundName = $fundNames[$model->fund_id instanceof FUND_TYPE ? $model->fund_id->value : $model->fund_id];
  59. }
  60. return $dto;
  61. }
  62. public function getFundId():int
  63. {
  64. if($this->fundId instanceof FUND_TYPE){
  65. return $this->fundId->value;
  66. }
  67. return (int) $this->fundId;
  68. }
  69. /**
  70. * 转换为数组
  71. *
  72. * @return array
  73. */
  74. public function toArray(): array
  75. {
  76. $result = [
  77. 'id' => $this->id,
  78. 'user_id' => $this->userId,
  79. 'fund_id' => $this->fundId instanceof FUND_TYPE ? $this->fundId->value : $this->fundId,
  80. 'balance' => $this->balance,
  81. 'update_time' => $this->updateTime,
  82. 'create_time' => $this->createTime,
  83. ];
  84. if ($this->fundName !== null) {
  85. $result['fund_name'] = $this->fundName;
  86. }
  87. return $result;
  88. }
  89. }