ChestItemValidator.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Module\GameItems\Validators;
  3. use App\Module\GameItems\Enums\ITEM_TYPE;
  4. use App\Module\GameItems\Models\Item;
  5. use App\Module\GameItems\Models\ItemChestConfig;
  6. use UCore\Validator;
  7. /**
  8. * 宝箱物品验证器
  9. *
  10. * 验证物品是否为宝箱类型且配置正确
  11. */
  12. class ChestItemValidator extends Validator
  13. {
  14. /**
  15. * 验证宝箱物品
  16. *
  17. * @param mixed $value 物品ID
  18. * @param array $data 包含其他数据的数组
  19. * @return bool 验证是否通过
  20. */
  21. public function validate(mixed $value, array $data): bool
  22. {
  23. $itemId = (int)$value;
  24. try {
  25. // 获取物品信息
  26. $item = Item::find($itemId);
  27. if (!$item) {
  28. $this->addError("物品不存在");
  29. return false;
  30. }
  31. // 检查是否为宝箱类型
  32. if ($item->type !== ITEM_TYPE::CHEST) {
  33. $this->addError("该物品不是宝箱类型");
  34. return false;
  35. }
  36. // 检查宝箱是否有配置
  37. $chestConfig = ItemChestConfig::where('item_id', $itemId)
  38. ->where('is_active', true)
  39. ->first();
  40. if (!$chestConfig) {
  41. $this->addError("宝箱没有配置或配置未激活");
  42. return false;
  43. }
  44. // 检查是否配置了奖励组
  45. if (!$chestConfig->reward_group_id) {
  46. $this->addError("宝箱没有配置奖励组");
  47. return false;
  48. }
  49. // 将宝箱信息保存到验证对象中,供后续使用
  50. $chestItemKey = $this->args[0] ?? null;
  51. if ($chestItemKey) {
  52. $this->validation->$chestItemKey = $item;
  53. }
  54. return true;
  55. } catch (\Exception $e) {
  56. $this->addError('验证宝箱物品时发生错误: ' . $e->getMessage());
  57. return false;
  58. }
  59. }
  60. }