UserSkinDto.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Module\Game\Dto;
  3. use App\Module\Game\Models\GameUserSkin;
  4. use UCore\Dto\BaseDto;
  5. /**
  6. * 用户皮肤DTO
  7. */
  8. class UserSkinDto extends BaseDto
  9. {
  10. /**
  11. * 用户ID
  12. *
  13. * @var int
  14. */
  15. public int $userId;
  16. /**
  17. * 当前使用的皮肤ID
  18. *
  19. * @var int
  20. */
  21. public int $currentSkinId;
  22. /**
  23. * 拥有的皮肤ID数组
  24. *
  25. * @var array
  26. */
  27. public array $ownedSkins;
  28. /**
  29. * 当前皮肤名称
  30. *
  31. * @var string
  32. */
  33. public string $currentSkinName;
  34. /**
  35. * 拥有的皮肤详情(包含ID和名称)
  36. *
  37. * @var array
  38. */
  39. public array $ownedSkinsDetail;
  40. /**
  41. * 从模型创建DTO
  42. *
  43. * @param GameUserSkin $model
  44. * @return static
  45. */
  46. public static function fromModel(GameUserSkin $model): static
  47. {
  48. $dto = new static();
  49. $dto->userId = $model->user_id;
  50. $dto->currentSkinId = $model->current_skin_id;
  51. $dto->ownedSkins = $model->getOwnedSkinsArrayAttribute();
  52. $dto->currentSkinName = GameUserSkin::getSkinName($model->current_skin_id);
  53. // 构建拥有的皮肤详情
  54. $dto->ownedSkinsDetail = [];
  55. foreach ($dto->ownedSkins as $skinId) {
  56. $dto->ownedSkinsDetail[] = [
  57. 'id' => $skinId,
  58. 'name' => GameUserSkin::getSkinName($skinId),
  59. 'is_current' => $skinId === $dto->currentSkinId,
  60. ];
  61. }
  62. return $dto;
  63. }
  64. /**
  65. * 转换为数组
  66. *
  67. * @return array
  68. */
  69. public function toArray(): array
  70. {
  71. return [
  72. 'user_id' => $this->userId,
  73. 'current_skin_id' => $this->currentSkinId,
  74. 'current_skin_name' => $this->currentSkinName,
  75. 'owned_skins' => $this->ownedSkins,
  76. 'owned_skins_detail' => $this->ownedSkinsDetail,
  77. ];
  78. }
  79. /**
  80. * 检查是否拥有指定皮肤
  81. *
  82. * @param int $skinId
  83. * @return bool
  84. */
  85. public function hasSkin(int $skinId): bool
  86. {
  87. return in_array($skinId, $this->ownedSkins);
  88. }
  89. /**
  90. * 获取拥有的皮肤数量
  91. *
  92. * @return int
  93. */
  94. public function getOwnedSkinsCount(): int
  95. {
  96. return count($this->ownedSkins);
  97. }
  98. }