ItemOwnershipValidator.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\GameItems\Services\ItemService;
  4. use UCore\Validator;
  5. /**
  6. * 物品归属验证器
  7. *
  8. * 验证用户是否拥有指定的物品和数量
  9. */
  10. class ItemOwnershipValidator extends Validator
  11. {
  12. /**
  13. * 验证物品归属
  14. *
  15. * @param mixed $value 物品ID
  16. * @param array $data 包含用户ID、实例ID和数量的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. $itemId = (int)$value;
  22. // 从 args 获取参数键名
  23. $userIdKey = $this->args[0] ?? 'user_id';
  24. $instanceIdKey = $this->args[1] ?? 'instance_id';
  25. $quantityKey = $this->args[2] ?? 'quantity';
  26. $userId = $data[$userIdKey] ?? null;
  27. $instanceId = $data[$instanceIdKey] ?? 0;
  28. $requiredQuantity = $data[$quantityKey] ?? 1;
  29. if (!$userId) {
  30. $this->addError('用户ID不能为空');
  31. return false;
  32. }
  33. try {
  34. // 如果指定了实例ID,检查特定实例
  35. if ($instanceId > 0) {
  36. $userItem = ItemService::getUserItem($userId, $itemId, $instanceId);
  37. if (!$userItem) {
  38. $this->addError('指定的物品实例不存在');
  39. return false;
  40. }
  41. if ($userItem->quantity < $requiredQuantity) {
  42. $this->addError("物品数量不足,需要{$requiredQuantity}个,当前拥有{$userItem->quantity}个");
  43. return false;
  44. }
  45. } else {
  46. // 检查用户是否拥有足够数量的该物品
  47. $userItems = ItemService::getUserItems($userId, ['item_id' => $itemId]);
  48. if ($userItems->isEmpty()) {
  49. $this->addError('您没有该物品');
  50. return false;
  51. }
  52. $totalQuantity = $userItems->sum('quantity');
  53. if ($totalQuantity < $requiredQuantity) {
  54. $this->addError("物品数量不足,需要{$requiredQuantity}个,当前拥有{$totalQuantity}个");
  55. return false;
  56. }
  57. }
  58. return true;
  59. } catch (\Exception $e) {
  60. $this->addError('验证物品归属时发生错误: ' . $e->getMessage());
  61. return false;
  62. }
  63. }
  64. }