RemoveToolValidator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\GameItems\Services\ItemService;
  4. use UCore\Validator;
  5. /**
  6. * 铲除工具验证器
  7. *
  8. * 验证用户是否拥有铲除工具(如果需要)
  9. */
  10. class RemoveToolValidator extends Validator
  11. {
  12. /**
  13. * 验证铲除工具
  14. *
  15. * @param mixed $value 工具物品ID
  16. * @param array $data 包含用户ID的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. $toolItemId = (int)$value;
  22. // 如果没有提供工具ID,则跳过验证(允许不使用工具)
  23. if ($toolItemId <= 0) {
  24. return true;
  25. }
  26. // 从 args 获取用户ID的键名
  27. $userIdKey = $this->args[0] ?? 'user_id';
  28. $userId = $data[$userIdKey] ?? null;
  29. if (!$userId) {
  30. $this->addError('用户ID不能为空');
  31. return false;
  32. }
  33. try {
  34. // 检查用户是否拥有该工具
  35. $userItems = ItemService::getUserItems($userId, ['item_id' => $toolItemId]);
  36. if ($userItems->isEmpty()) {
  37. $this->addError('您没有该铲除工具');
  38. return false;
  39. }
  40. $totalQuantity = $userItems->sum('quantity');
  41. if ($totalQuantity <= 0) {
  42. $this->addError('铲除工具数量不足');
  43. return false;
  44. }
  45. return true;
  46. } catch (\Exception $e) {
  47. $this->addError('验证铲除工具时发生错误: ' . $e->getMessage());
  48. return false;
  49. }
  50. }
  51. }