FertilizerItemValidator.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\GameItems\Models\Item;
  4. use App\Module\GameItems\Services\ItemService;
  5. use Illuminate\Support\Facades\Log;
  6. use UCore\Validator;
  7. /**
  8. * 肥料物品验证器
  9. *
  10. * 验证物品是否为有效的肥料,并获取肥料属性
  11. */
  12. class FertilizerItemValidator 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. try {
  24. Log::info('FertilizerItemValidator开始验证', [
  25. 'item_id' => $value,
  26. 'data' => $data
  27. ]);
  28. // 获取物品信息
  29. $item = Item::find($value);
  30. if (!$item) {
  31. Log::warning('FertilizerItemValidator: 物品不存在', ['item_id' => $value]);
  32. $this->addError('物品不存在');
  33. return false;
  34. }
  35. // 获取肥料的crop_growth_time属性
  36. $cropGrowthTime = ItemService::getItemNumericAttribute($value, 'crop_growth_time', 0);
  37. Log::info('FertilizerItemValidator: 获取到crop_growth_time', [
  38. 'item_id' => $value,
  39. 'crop_growth_time' => $cropGrowthTime
  40. ]);
  41. // 验证是否为有效的肥料(crop_growth_time > 0)
  42. if ($cropGrowthTime <= 0) {
  43. Log::warning('FertilizerItemValidator: 物品不是有效的肥料', [
  44. 'item_id' => $value,
  45. 'crop_growth_time' => $cropGrowthTime
  46. ]);
  47. $this->addError('该物品不是有效的肥料');
  48. return false;
  49. }
  50. // 设置验证对象的属性
  51. if (isset($this->args[0])) {
  52. $this->validation->{$this->args[0]} = $item;
  53. }
  54. if (isset($this->args[1])) {
  55. $this->validation->{$this->args[1]} = $cropGrowthTime;
  56. }
  57. Log::info('FertilizerItemValidator: 验证通过', [
  58. 'item_id' => $value,
  59. 'crop_growth_time' => $cropGrowthTime
  60. ]);
  61. return true;
  62. } catch (\Exception $e) {
  63. $this->addError('验证肥料物品时发生错误:' . $e->getMessage());
  64. return false;
  65. }
  66. }
  67. }