| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <?php
- namespace App\Module\Shop\Validators;
- use App\Module\Game\Services\ConsumeService;
- use UCore\Validator;
- /**
- * 商店资金验证器
- *
- * 验证用户资金是否充足
- */
- class ShopFundValidator 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->consume_group_id) {
- // 循环检查每个购买数量的消耗条件
- for ($i = 0; $i < $number; $i++) {
- $consumeValidation = ConsumeService::checkConsume($userId, $shopItem->consume_group_id);
- if (!$consumeValidation->success) {
- $this->addError($consumeValidation->message);
- return false;
- }
- }
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证消耗条件时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|