LandUpgradeHouseLevelValidator.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\Farm\Models\FarmLandType;
  4. use App\Module\Farm\Models\FarmUser;
  5. use Illuminate\Support\Facades\Log;
  6. use UCore\Validator;
  7. /**
  8. * 土地升级房屋等级验证器
  9. *
  10. * 验证用户房屋等级是否满足土地升级要求
  11. */
  12. class LandUpgradeHouseLevelValidator extends Validator
  13. {
  14. /**
  15. * 验证房屋等级
  16. *
  17. * @param mixed $value 土地ID
  18. * @param array $data 包含用户ID的数组
  19. * @return bool 验证是否通过
  20. */
  21. public function validate(mixed $value, array $data): bool
  22. {
  23. // 从 args 获取参数
  24. $userIdKey = $this->args[0] ?? 'user_id';
  25. $upgradeConfigKey = $this->args[1] ?? 'upgrade_config';
  26. $userId = $data[$userIdKey] ?? null;
  27. $upgradeConfig = $this->validation->$upgradeConfigKey ?? null;
  28. if (!$userId) {
  29. $this->addError('用户ID不能为空');
  30. return false;
  31. }
  32. if (!$upgradeConfig) {
  33. $this->addError('升级配置不存在,请先验证升级路径');
  34. return false;
  35. }
  36. try {
  37. // 获取目标土地类型
  38. $targetLandType = FarmLandType::find($upgradeConfig->to_type_id);
  39. if (!$targetLandType) {
  40. $this->addError('目标土地类型不存在');
  41. return false;
  42. }
  43. // 获取用户房屋信息
  44. $farmUser = FarmUser::where('user_id', $userId)->first();
  45. if (!$farmUser) {
  46. $this->addError('用户农场信息不存在');
  47. return false;
  48. }
  49. // 检查房屋等级是否满足要求
  50. if ($farmUser->house_level < $targetLandType->unlock_house_level) {
  51. $this->addError("房屋等级不足,需要{$targetLandType->unlock_house_level}级,当前{$farmUser->house_level}级");
  52. return false;
  53. }
  54. return true;
  55. } catch (\Exception $e) {
  56. Log::error('验证房屋等级时发生错误', [
  57. 'user_id' => $userId,
  58. 'error' => $e->getMessage(),
  59. 'trace' => $e->getTraceAsString()
  60. ]);
  61. $this->addError('验证房屋等级时发生错误: ' . $e->getMessage());
  62. return false;
  63. }
  64. }
  65. }