PickSourceValidator.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Module\Farm\Validators;
  3. use UCore\Validation\BaseValidator;
  4. /**
  5. * 摘取来源验证器
  6. * 验证摘取来源信息
  7. */
  8. class PickSourceValidator extends BaseValidator
  9. {
  10. // 允许的摘取来源类型
  11. private const ALLOWED_SOURCES = [
  12. 'manual', // 手动摘取
  13. 'friend_visit', // 好友访问摘取
  14. 'system_auto', // 系统自动摘取
  15. 'task_reward', // 任务奖励摘取
  16. 'event_bonus', // 活动奖励摘取
  17. ];
  18. /**
  19. * 验证摘取来源
  20. *
  21. * @param string $pickSource 摘取来源
  22. * @param int|null $sourceId 来源ID
  23. * @return bool
  24. */
  25. public function validate(string $pickSource, ?int $sourceId = null): bool
  26. {
  27. // 验证摘取来源字符串格式
  28. if (empty($pickSource)) {
  29. $this->addError('摘取来源不能为空');
  30. return false;
  31. }
  32. if (!in_array($pickSource, self::ALLOWED_SOURCES)) {
  33. $allowedSources = implode(', ', self::ALLOWED_SOURCES);
  34. $this->addError("无效的摘取来源: {$pickSource},允许的来源: {$allowedSources}");
  35. return false;
  36. }
  37. // 检查来源ID的有效性(如果提供)
  38. if ($sourceId !== null && $sourceId <= 0) {
  39. $this->addError('来源ID必须大于0');
  40. return false;
  41. }
  42. // 某些来源类型需要提供来源ID
  43. $requireSourceId = ['friend_visit', 'task_reward', 'event_bonus'];
  44. if (in_array($pickSource, $requireSourceId) && $sourceId === null) {
  45. $this->addError("摘取来源 {$pickSource} 需要提供来源ID");
  46. return false;
  47. }
  48. return true;
  49. }
  50. /**
  51. * 获取允许的摘取来源列表
  52. *
  53. * @return array
  54. */
  55. public static function getAllowedSources(): array
  56. {
  57. return self::ALLOWED_SOURCES;
  58. }
  59. }