DiamondWithdrawValidation.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace App\Module\OpenAPI\Validations;
  3. use App\Module\OpenAPI\Validators\DiamondAmountValidator;
  4. use App\Module\OpenAPI\Validators\UserExistenceValidator;
  5. use UCore\ValidationCore;
  6. /**
  7. * 钻石提取验证类
  8. *
  9. * 验证钻石提取请求的参数
  10. */
  11. class DiamondWithdrawValidation extends ValidationCore
  12. {
  13. /**
  14. * 用户对象,由 UserExistenceValidator 设置
  15. */
  16. public ?\App\Module\User\Models\User $user = null;
  17. /**
  18. * 格式化后的金额,由 DiamondAmountValidator 设置
  19. */
  20. public ?float $formattedAmount = null;
  21. /**
  22. * 验证规则
  23. *
  24. * @param array $rules 额外规则
  25. * @return array
  26. */
  27. public function rules($rules = []): array
  28. {
  29. return [
  30. // 基础字段验证
  31. ['user_id', 'required'],
  32. ['user_id', 'integer'],
  33. ['user_id', 'min', 'range' => 1],
  34. ['amount', 'required'],
  35. ['amount', 'number'],
  36. ['amount', 'min', 'range' => 0.0000000001], // 最小金额 0.0000000001 钻石
  37. // 可选字段验证
  38. ['order_id', 'string'],
  39. ['order_id', 'max', 'range' => 100],
  40. ['remark', 'string'],
  41. ['remark', 'max', 'range' => 255],
  42. // 业务验证(按顺序执行)
  43. [
  44. 'user_id',
  45. new UserExistenceValidator($this, ['user']),
  46. 'msg' => '源用户不存在或状态异常',
  47. 'when' => function($data) {
  48. return isset($data['user_id']);
  49. }
  50. ],
  51. [
  52. 'amount',
  53. new DiamondAmountValidator($this, ['formattedAmount']),
  54. 'msg' => '钻石金额格式错误或超出精度范围',
  55. 'when' => function($data) {
  56. return isset($data['amount']);
  57. }
  58. ],
  59. ];
  60. }
  61. /**
  62. * 获取验证后的安全数据
  63. *
  64. * @param bool $asObject 是否返回对象
  65. * @return array|object
  66. */
  67. public function getSafeData(bool $asObject = false): array|object
  68. {
  69. $data = parent::getSafeData($asObject);
  70. // 如果返回对象,直接返回
  71. if ($asObject) {
  72. return $data;
  73. }
  74. // 使用格式化后的金额
  75. if ($this->formattedAmount !== null) {
  76. $data['amount'] = $this->formattedAmount;
  77. }
  78. return $data;
  79. }
  80. /**
  81. * 获取字段标签
  82. *
  83. * @return array
  84. */
  85. public function attributeLabels(): array
  86. {
  87. return [
  88. 'user_id' => '源用户ID',
  89. 'amount' => '提取金额',
  90. 'order_id' => '订单号',
  91. 'remark' => '备注',
  92. ];
  93. }
  94. }