| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- namespace App\Module\Pet\Validators;
- use App\Module\Pet\Enums\PetStatus;
- use App\Module\Pet\Models\PetSkill;
- use App\Module\Pet\Models\PetUser;
- use UCore\Validator;
- use UCore\Validator\ValidationMessage;
- /**
- * 宠物技能使用验证器
- *
- * 用于验证宠物技能使用条件的合法性
- */
- class PetSkillUseValidator extends Validator
- {
- use ValidationMessage;
-
- /**
- * 验证方法
- *
- * @param mixed $value 宠物ID
- * @param array $data 所有数据
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $petId = $value;
- $skillId = $data['skillId'] ?? 0;
-
- try {
- // 获取宠物信息
- $pet = PetUser::find($petId);
-
- if (!$pet) {
- $this->throwMessage([], '宠物不存在');
- return false;
- }
-
- // 获取技能信息
- $skill = PetSkill::find($skillId);
- if (!$skill) {
- $this->throwMessage(['skillId' => $skillId], '技能({skillId})不存在');
- return false;
- }
-
- // 检查宠物状态
- if ($pet->status !== PetStatus::NORMAL) {
- $this->throwMessage(['status' => $pet->status->value], '宠物当前状态({status})不允许使用技能');
- return false;
- }
-
- // 检查宠物等级是否满足技能要求
- if ($pet->level < $skill->min_level) {
- $this->throwMessage([
- 'level' => $pet->level,
- 'required' => $skill->min_level
- ], '宠物等级({level})不足,需要等级({required})才能使用该技能');
- return false;
- }
-
- // 检查宠物体力是否足够
- if ($pet->stamina < $skill->stamina_cost) {
- $this->throwMessage([
- 'stamina' => $pet->stamina,
- 'required' => $skill->stamina_cost
- ], '宠物体力({stamina})不足,需要体力({required})才能使用该技能');
- return false;
- }
-
- // 检查技能冷却时间
- $lastUsed = $pet->skillLogs()
- ->where('skill_id', $skillId)
- ->orderBy('used_at', 'desc')
- ->first();
-
- if ($lastUsed) {
- $cooldownSeconds = $skill->cool_down;
- $secondsSinceLastUse = now()->diffInSeconds($lastUsed->used_at);
-
- if ($secondsSinceLastUse < $cooldownSeconds) {
- $remainingCooldown = $cooldownSeconds - $secondsSinceLastUse;
- $this->throwMessage(['remaining' => $remainingCooldown], '技能冷却中,还需等待{remaining}秒');
- return false;
- }
- }
-
- return true;
- } catch (\Exception $e) {
- $this->throwMessage(['error' => $e->getMessage()], '验证过程发生错误: {error}');
- return false;
- }
- }
- }
|