ItemQuantityValidator.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\GameItems\Logics\ItemQuantity;
  4. use UCore\Validator;
  5. /**
  6. * 物品数量验证器
  7. *
  8. * 用于验证用户是否拥有足够数量的物品
  9. */
  10. class ItemQuantityValidator extends Validator
  11. {
  12. /**
  13. * 验证方法
  14. *
  15. * @param mixed $value 物品ID
  16. * @param array $data 包含用户ID和数量的数组
  17. * @return bool 验证是否通过
  18. *
  19. * 注意:
  20. * - $this->args[0] 可以指定用户ID的键名,默认为 'user_id'
  21. * - $this->args[1] 可以指定数量的键名,默认为 'quantity'
  22. * - $this->args[2] 可以指定实例ID的键名,默认为 'instance_id'
  23. * - $this->args[3] 可以指定是否包含所有类型物品的标志,默认为 false(只验证普通物品)
  24. */
  25. public function validate(mixed $value, array $data): bool
  26. {
  27. $itemId = (int)$value;
  28. // 从 args 获取字段键名,如果未提供则使用默认值
  29. $userIdKey = $this->args[0] ?? 'user_id';
  30. $quantityKey = $this->args[1] ?? 'quantity';
  31. $instanceIdKey = $this->args[2] ?? 'instance_id';
  32. $includeAllTypes = $this->args[3] ?? false;
  33. $userId = $data[$userIdKey] ?? 0;
  34. $quantity = $data[$quantityKey] ?? 1;
  35. $instanceId = $data[$instanceIdKey] ?? null;
  36. // 验证参数
  37. if ($itemId <= 0) {
  38. $this->addError('物品ID无效');
  39. return false;
  40. }
  41. if ($userId <= 0) {
  42. $this->addError('用户ID无效');
  43. return false;
  44. }
  45. if ($quantity <= 0) {
  46. $this->addError('物品数量必须大于0');
  47. return false;
  48. }
  49. try {
  50. // 根据不同情况进行验证
  51. if ($instanceId !== null) {
  52. // 验证特定实例物品
  53. $hasInstance = ItemQuantity::hasInstanceItem($userId, $itemId, $instanceId);
  54. if (!$hasInstance) {
  55. $this->addError("用户不拥有指定的实例物品(ID: {$instanceId})");
  56. return false;
  57. }
  58. return true;
  59. } else if ($includeAllTypes) {
  60. // 验证所有类型物品(普通物品和实例物品)的总数量
  61. $totalQuantity = ItemQuantity::getUserTotalItemQuantity($userId, $itemId);
  62. if ($totalQuantity < $quantity) {
  63. $this->addError("物品总数量不足,需要{$quantity}个,但只有{$totalQuantity}个");
  64. return false;
  65. }
  66. return true;
  67. } else {
  68. // 只验证普通物品数量
  69. $normalQuantity = ItemQuantity::getUserItemQuantity($userId, $itemId);
  70. if ($normalQuantity < $quantity) {
  71. $this->addError("普通物品 $itemId 数量不足,需要{$quantity}个,但只有{$normalQuantity}个");
  72. return false;
  73. }
  74. return true;
  75. }
  76. } catch (\Exception $e) {
  77. $this->addError('验证物品数量时发生错误: ' . $e->getMessage());
  78. return false;
  79. }
  80. }
  81. }