| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- <?php
- namespace App\Module\OpenAPI\Validations;
- use App\Module\OpenAPI\Validators\DiamondAmountValidator;
- use App\Module\OpenAPI\Validators\UserExistenceValidator;
- use UCore\ValidationCore;
- /**
- * 钻石提取验证类
- *
- * 验证钻石提取请求的参数
- */
- class DiamondWithdrawValidation extends ValidationCore
- {
- /**
- * 用户对象,由 UserExistenceValidator 设置
- */
- public ?\App\Module\User\Models\User $user = null;
- /**
- * 格式化后的金额,由 DiamondAmountValidator 设置
- */
- public ?float $formattedAmount = null;
- /**
- * 验证规则
- *
- * @param array $rules 额外规则
- * @return array
- */
- public function rules($rules = []): array
- {
- return [
- // 基础字段验证
- ['user_id', 'required'],
- ['user_id', 'integer'],
- ['user_id', 'min', 'range' => 1],
-
- ['amount', 'required'],
- ['amount', 'number'],
- ['amount', 'min', 'range' => 0.0000000001], // 最小金额 0.0000000001 钻石
-
- // 可选字段验证
- ['order_id', 'string'],
- ['order_id', 'max', 'range' => 100],
-
- ['remark', 'string'],
- ['remark', 'max', 'range' => 255],
-
- // 业务验证(按顺序执行)
- [
- 'user_id',
- new UserExistenceValidator($this, ['user']),
- 'msg' => '源用户不存在或状态异常',
- 'when' => function($data) {
- return isset($data['user_id']);
- }
- ],
-
- [
- 'amount',
- new DiamondAmountValidator($this, ['formattedAmount']),
- 'msg' => '钻石金额格式错误或超出精度范围',
- 'when' => function($data) {
- return isset($data['amount']);
- }
- ],
- ];
- }
- /**
- * 获取验证后的安全数据
- *
- * @param bool $asObject 是否返回对象
- * @return array|object
- */
- public function getSafeData(bool $asObject = false): array|object
- {
- $data = parent::getSafeData($asObject);
- // 如果返回对象,直接返回
- if ($asObject) {
- return $data;
- }
- // 使用格式化后的金额
- if ($this->formattedAmount !== null) {
- $data['amount'] = $this->formattedAmount;
- }
- return $data;
- }
- /**
- * 获取字段标签
- *
- * @return array
- */
- public function attributeLabels(): array
- {
- return [
- 'user_id' => '源用户ID',
- 'amount' => '提取金额',
- 'order_id' => '订单号',
- 'remark' => '备注',
- ];
- }
- }
|