| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- <?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;
- }
- // 使用新的统一限购检查方法
- list($canPurchase, $errorMessage, $remainingQuantity) = $shopItem->canUserPurchaseWithLimits($userId, $number);
- if (!$canPurchase) {
- $this->addError($errorMessage);
- return false;
- }
- return true;
- }
- }
|