| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <?php
- namespace App\Module\Farm\Validators;
- use App\Module\Game\Services\ConsumeService;
- use UCore\Validator;
- /**
- * 土地升级材料验证器
- *
- * 验证用户是否拥有足够的升级材料
- */
- class LandUpgradeMaterialsValidator extends Validator
- {
- /**
- * 验证土地升级材料
- *
- * @param mixed $value 土地ID
- * @param array $data 包含用户ID的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- // 从 args 获取用户ID的键名,默认为 'user_id'
- $userIdKey = $this->args[0] ?? 'user_id';
- $userId = $data[$userIdKey] ?? null;
- if (!$userId) {
- $this->addError('用户ID不能为空');
- return false;
- }
- // 从 args 获取升级配置的键名
- $upgradeConfigKey = $this->args[1] ?? 'upgrade_config';
- $upgradeConfig = $this->validation->$upgradeConfigKey ?? null;
- if (!$upgradeConfig) {
- $this->addError('升级配置不存在,请先验证升级路径');
- return false;
- }
- try {
- // 检查消耗条件
- $checkResult = ConsumeService::checkConsume($userId, $upgradeConfig->materials);
-
- if ($checkResult->error) {
- $this->addError($checkResult->message);
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证升级材料时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|