| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace App\Module\GameItems\Validators;
- use App\Module\GameItems\Models\ItemChestConfig;
- use App\Module\Game\Services\ConsumeService;
- use UCore\Validator;
- /**
- * 宝箱消耗验证器
- *
- * 验证用户是否满足宝箱开启的消耗条件
- */
- class ChestConsumeValidator extends Validator
- {
- /**
- * 验证宝箱消耗
- *
- * @param mixed $value 宝箱物品ID
- * @param array $data 包含用户ID和数量的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $chestId = (int)$value;
-
- // 从 args 获取参数键名
- $userIdKey = $this->args[0] ?? 'user_id';
- $quantityKey = $this->args[1] ?? 'quantity';
- $userId = $data[$userIdKey] ?? null;
- $quantity = $data[$quantityKey] ?? 1;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- try {
- // 获取宝箱配置
- $chestConfig = ItemChestConfig::where('item_id', $chestId)
- ->where('is_active', true)
- ->first();
- if (!$chestConfig) {
- $this->addError('宝箱配置不存在或未激活');
- return false;
- }
- // 如果没有配置消耗组,则无需验证消耗
- if (!$chestConfig->consume_group_id) {
- return true;
- }
- // 检查消耗组条件
- $checkResult = ConsumeService::checkConsume($userId, $chestConfig->consume_group_id);
-
- if (!$checkResult->success) {
- $this->addError($checkResult->message);
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证宝箱消耗时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|