PetOwnershipValidator.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Module\Pet\Validators;
  3. use App\Module\Pet\Models\PetUser;
  4. use App\Module\Pet\Enums\PetStatus;
  5. use UCore\Validator;
  6. /**
  7. * 宠物归属权和状态验证器
  8. *
  9. * 用于验证宠物是否属于指定用户且状态为空闲
  10. */
  11. class PetOwnershipValidator extends Validator
  12. {
  13. /**
  14. * 验证宠物归属权和状态
  15. *
  16. * @param mixed $value 宠物ID
  17. * @param array $data 包含用户ID等信息的数组
  18. * @return bool 验证是否通过
  19. */
  20. public function validate(mixed $value, array $data): bool
  21. {
  22. $petId = (int)$value;
  23. if ($petId <= 0) {
  24. $this->addError('宠物ID必须大于0');
  25. return false;
  26. }
  27. // 从 args 获取用户ID字段键名
  28. $userIdKey = $this->args[0] ?? 'current_user_id';
  29. $userId = $data[$userIdKey] ?? null;
  30. if (!$userId) {
  31. $this->addError('用户ID不能为空');
  32. return false;
  33. }
  34. try {
  35. // 查找宠物
  36. $pet = PetUser::where('id', $petId)
  37. ->where('user_id', $userId)
  38. ->first();
  39. if (!$pet) {
  40. $this->addError('宠物不存在或不属于当前用户');
  41. return false;
  42. }
  43. // 检查宠物状态是否为正常(空闲)
  44. if ($pet->status !== PetStatus::NORMAL) {
  45. $statusName = match($pet->status) {
  46. PetStatus::FIGHTING => '战斗中',
  47. PetStatus::DEAD => '死亡',
  48. PetStatus::FEEDING => '喂养中',
  49. PetStatus::TRAINING => '训练中',
  50. PetStatus::RESTING => '休息中',
  51. PetStatus::TRAVELING => '外出中',
  52. default => '未知状态'
  53. };
  54. $this->addError("宠物当前状态为{$statusName},无法执行操作");
  55. return false;
  56. }
  57. // 检查宠物体力是否足够(偷菜需要至少20体力)
  58. if ($pet->stamina < 20) {
  59. $this->addError('宠物体力不足,至少需要20点体力');
  60. return false;
  61. }
  62. return true;
  63. } catch (\Exception $e) {
  64. $this->addError('宠物验证过程发生错误: ' . $e->getMessage());
  65. return false;
  66. }
  67. }
  68. }