SeedItemValidator.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\GameItems\Enums\ITEM_TYPE;
  4. use App\Module\GameItems\Models\Item;
  5. use App\Module\Farm\Models\FarmSeed;
  6. use UCore\Validator;
  7. /**
  8. * 种子物品验证器
  9. *
  10. * 验证物品是否为种子类型且配置正确
  11. */
  12. class SeedItemValidator 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. $seedConfig = FarmSeed::where('item_id', $itemId)->first();
  33. if (!$seedConfig) {
  34. $this->addError("种子没有配置信息");
  35. return false;
  36. }
  37. // 将种子信息保存到验证对象中,供后续使用
  38. $seedItemKey = $this->args[0] ?? null;
  39. if ($seedItemKey) {
  40. $this->validation->$seedItemKey = $item;
  41. }
  42. return true;
  43. } catch (\Exception $e) {
  44. $this->addError('验证种子物品时发生错误: ' . $e->getMessage());
  45. return false;
  46. }
  47. }
  48. }