| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?php
- namespace App\Module\Shop\Validators;
- use UCore\Validator;
- /**
- * 商店购买限制验证器
- *
- * 验证用户购买数量是否超出限制
- */
- class ShopBuyLimitValidator extends Validator
- {
- /**
- * 验证购买限制
- *
- * @param mixed $value 商品ID
- * @param array $data 包含用户ID和购买数量的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- // 从 args 获取参数键名
- $userIdKey = $this->args[0] ?? 'user_id';
- $numberKey = $this->args[1] ?? 'number';
- $shopItemKey = $this->args[2] ?? 'shop_item';
- $userId = $data[$userIdKey] ?? null;
- $number = $data[$numberKey] ?? null;
- $shopItem = $this->validation->$shopItemKey ?? null;
- if (!$userId || !$number || !$shopItem) {
- $this->addError('验证购买限制时缺少必要参数');
- return false;
- }
- try {
- // 检查购买限制
- if ($shopItem->max_buy > 0) {
- // 获取用户已购买数量
- $boughtCount = $shopItem->getUserBoughtCount($userId);
- if ($boughtCount + $number > $shopItem->max_buy) {
- $remainingCount = $shopItem->max_buy - $boughtCount;
- $this->addError("超出购买限制,最多还能购买{$remainingCount}个");
- return false;
- }
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证购买限制时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|