ChestOwnershipValidator.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 ChestOwnershipValidator 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. $userId = $data[$userIdKey] ?? null;
  26. $instanceId = $data[$instanceIdKey] ?? null;
  27. if (!$userId) {
  28. $this->addError('用户ID不能为空');
  29. return false;
  30. }
  31. try {
  32. // 检查用户是否拥有该宝箱
  33. $userItem = ItemService::getUserItem($userId, $itemId, $instanceId);
  34. if (!$userItem) {
  35. $this->addError('您没有该宝箱或宝箱不存在');
  36. return false;
  37. }
  38. if ($userItem->quantity <= 0) {
  39. $this->addError('宝箱数量不足');
  40. return false;
  41. }
  42. return true;
  43. } catch (\Exception $e) {
  44. $this->addError('验证宝箱归属时发生错误: ' . $e->getMessage());
  45. return false;
  46. }
  47. }
  48. }