PetStealValidator.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Module\Pet\Validators;
  3. use App\Module\Pet\Services\PetStealService;
  4. use App\Module\Farm\Models\FarmCrop;
  5. use UCore\Validator;
  6. /**
  7. * 宠物偷菜验证器
  8. *
  9. * 用于验证宠物偷菜操作是否有效
  10. */
  11. class PetStealValidator extends Validator
  12. {
  13. /**
  14. * 验证偷菜操作
  15. *
  16. * @param mixed $value 作物ID (plantId)
  17. * @param array $data 包含用户ID等信息的数组
  18. * @return bool 验证是否通过
  19. */
  20. public function validate(mixed $value, array $data): bool
  21. {
  22. $plantId = (int)$value;
  23. // 从 args 获取字段键名
  24. $stealerIdKey = $this->args[0] ?? 'user_id'; // 偷菜者用户ID键名
  25. $targetUserIdKey = $this->args[1] ?? 'userId'; // 被偷者用户ID键名
  26. $stealerId = $data[$stealerIdKey] ?? null;
  27. $targetUserId = $data[$targetUserIdKey] ?? null;
  28. if (!$stealerId) {
  29. $this->addError('偷菜者用户ID不能为空');
  30. return false;
  31. }
  32. if (!$targetUserId) {
  33. $this->addError('被偷者用户ID不能为空');
  34. return false;
  35. }
  36. try {
  37. // 通过作物ID获取作物信息
  38. $crop = FarmCrop::find($plantId);
  39. if (!$crop) {
  40. $this->addError("作物{$plantId}不存在");
  41. return false;
  42. }
  43. // 获取土地ID
  44. $landId = $crop->land_id;
  45. // 检查作物是否属于目标用户
  46. if ($crop->user_id != $targetUserId) {
  47. $this->addError("作物{$plantId}属于用户{$crop->user_id},不属于目标用户{$targetUserId}");
  48. return false;
  49. }
  50. // 使用PetStealService检查是否可以偷菜
  51. $canStealResult = PetStealService::canSteal($stealerId, $targetUserId, $landId);
  52. if (!$canStealResult['can_steal']) {
  53. $this->addError($canStealResult['reason']);
  54. return false;
  55. }
  56. return true;
  57. } catch (\Exception $e) {
  58. $this->addError('偷菜验证过程发生错误: ' . $e->getMessage());
  59. return false;
  60. }
  61. }
  62. }