ShopItemValidator.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Module\Shop\Validators;
  3. use App\Module\Shop\Models\ShopItem;
  4. use UCore\Validator;
  5. /**
  6. * 商品验证器
  7. *
  8. * 验证商品是否存在且可购买
  9. */
  10. class ShopItemValidator extends Validator
  11. {
  12. /**
  13. * 验证商品
  14. *
  15. * @param mixed $value 商品ID
  16. * @param array $data 包含其他数据的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. $goodId = (int)$value;
  22. try {
  23. // 获取商品信息
  24. $shopItem = ShopItem::find($goodId);
  25. if (!$shopItem) {
  26. $this->addError("商品不存在");
  27. return false;
  28. }
  29. if (!$shopItem->is_active) {
  30. $this->addError("该商品已下架");
  31. return false;
  32. }
  33. // 将商品信息保存到验证对象中,供后续使用
  34. $shopItemKey = $this->args[0] ?? null;
  35. if ($shopItemKey) {
  36. $this->validation->$shopItemKey = $shopItem;
  37. }
  38. return true;
  39. } catch (\Exception $e) {
  40. $this->addError('验证商品时发生错误: ' . $e->getMessage());
  41. return false;
  42. }
  43. }
  44. }