PetSkillUseValidator.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Module\Pet\Validators;
  3. use App\Module\Pet\Enums\PetStatus;
  4. use App\Module\Pet\Models\PetSkill;
  5. use App\Module\Pet\Models\PetUser;
  6. use UCore\Validator;
  7. use UCore\Validator\ValidationMessage;
  8. /**
  9. * 宠物技能使用验证器
  10. *
  11. * 用于验证宠物技能使用条件的合法性
  12. */
  13. class PetSkillUseValidator extends Validator
  14. {
  15. use ValidationMessage;
  16. /**
  17. * 验证方法
  18. *
  19. * @param mixed $value 宠物ID
  20. * @param array $data 所有数据
  21. * @return bool 验证是否通过
  22. */
  23. public function validate(mixed $value, array $data): bool
  24. {
  25. $petId = $value;
  26. $skillId = $data['skillId'] ?? 0;
  27. try {
  28. // 获取宠物信息
  29. $pet = PetUser::find($petId);
  30. if (!$pet) {
  31. $this->throwMessage([], '宠物不存在');
  32. return false;
  33. }
  34. // 获取技能信息
  35. $skill = PetSkill::find($skillId);
  36. if (!$skill) {
  37. $this->throwMessage(['skillId' => $skillId], '技能({skillId})不存在');
  38. return false;
  39. }
  40. // 检查宠物状态
  41. if ($pet->status !== PetStatus::NORMAL) {
  42. $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许使用技能');
  43. return false;
  44. }
  45. // 检查宠物等级是否满足技能要求
  46. if ($pet->level < $skill->min_level) {
  47. $this->throwMessage([
  48. 'level' => $pet->level,
  49. 'required' => $skill->min_level
  50. ], '宠物等级({level})不足,需要等级({required})才能使用该技能');
  51. return false;
  52. }
  53. // 检查宠物体力是否足够
  54. if ($pet->stamina < $skill->stamina_cost) {
  55. $this->throwMessage([
  56. 'stamina' => $pet->stamina,
  57. 'required' => $skill->stamina_cost
  58. ], '宠物体力({stamina})不足,需要体力({required})才能使用该技能');
  59. return false;
  60. }
  61. // 检查技能冷却时间
  62. $lastUsed = $pet->skillLogs()
  63. ->where('skill_id', $skillId)
  64. ->orderBy('used_at', 'desc')
  65. ->first();
  66. if ($lastUsed) {
  67. $cooldownSeconds = $skill->cool_down;
  68. $secondsSinceLastUse = now()->diffInSeconds($lastUsed->used_at);
  69. if ($secondsSinceLastUse < $cooldownSeconds) {
  70. $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
  71. $this->throwMessage(['remaining' => $remainingCooldown], '技能冷却中,还需等待{remaining}秒');
  72. return false;
  73. }
  74. }
  75. return true;
  76. } catch (\Exception $e) {
  77. $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
  78. return false;
  79. }
  80. }
  81. }