LandUpgradePathValidator.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use App\Module\Farm\Models\FarmLand;
  4. use App\Module\Farm\Services\LandService;
  5. use UCore\Validator;
  6. /**
  7. * 土地升级路径验证器
  8. *
  9. * 验证土地是否有可用的升级路径
  10. */
  11. class LandUpgradePathValidator extends Validator
  12. {
  13. /**
  14. * 验证土地升级路径
  15. *
  16. * @param mixed $value 土地ID
  17. * @param array $data 包含用户ID的数组
  18. * @return bool 验证是否通过
  19. */
  20. public function validate(mixed $value, array $data): bool
  21. {
  22. $landId = (int)$value;
  23. // 从 args 获取用户ID的键名,默认为 'user_id'
  24. $userIdKey = $this->args[0] ?? 'user_id';
  25. $userId = $data[$userIdKey] ?? null;
  26. if (!$userId) {
  27. $this->addError('用户ID不能为空');
  28. return false;
  29. }
  30. try {
  31. // 获取可用的升级路径
  32. $upgradePaths = LandService::getAvailableUpgradePaths($userId, $landId);
  33. if (empty($upgradePaths)) {
  34. $this->addError('当前没有可用的升级路径');
  35. return false;
  36. }
  37. // 选择第一个可用的升级路径
  38. $upgradePath = $upgradePaths[0];
  39. // 获取土地信息
  40. $land = FarmLand::where('id', $landId)
  41. ->where('user_id', $userId)
  42. ->first();
  43. if (!$land) {
  44. $this->addError('土地不存在');
  45. return false;
  46. }
  47. // 获取升级配置(只检查配置是否存在,不进行其他验证)
  48. $upgradeConfig = \App\Module\Farm\Models\FarmLandUpgradeConfig::where('from_type_id', $land->land_type)
  49. ->where('to_type_id', $upgradePath['to_type_id'])
  50. ->first();
  51. if (!$upgradeConfig) {
  52. $this->addError('升级配置不存在');
  53. return false;
  54. }
  55. // 将升级配置保存到验证对象中,供后续使用
  56. $upgradeConfigKey = $this->args[1] ?? null;
  57. if ($upgradeConfigKey) {
  58. $this->validation->$upgradeConfigKey = $upgradeConfig;
  59. }
  60. return true;
  61. } catch (\Exception $e) {
  62. $this->addError('验证升级路径时发生错误: ' . $e->getMessage());
  63. return false;
  64. }
  65. }
  66. }