| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <?php
- namespace App\Module\Shop\Validators;
- use App\Module\Shop\Models\ShopItem;
- use UCore\Validator;
- /**
- * 商品验证器
- *
- * 验证商品是否存在且可购买
- */
- class ShopItemValidator extends Validator
- {
- /**
- * 验证商品
- *
- * @param mixed $value 商品ID
- * @param array $data 包含其他数据的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $goodId = (int)$value;
- try {
- // 获取商品信息
- $shopItem = ShopItem::find($goodId);
-
- if (!$shopItem) {
- $this->addError("商品不存在");
- return false;
- }
- if (!$shopItem->is_active) {
- $this->addError("该商品已下架");
- return false;
- }
- // 将商品信息保存到验证对象中,供后续使用
- $shopItemKey = $this->args[0] ?? null;
- if ($shopItemKey) {
- $this->validation->$shopItemKey = $shopItem;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证商品时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|