| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?php
- namespace App\Module\Shop\Validators;
- use App\Module\Fund\Services\AccountService;
- use UCore\Validator;
- /**
- * 商店资金验证器
- *
- * 验证用户资金是否充足
- */
- class ShopFundValidator extends Validator
- {
- /**
- * 验证用户资金
- *
- * @param mixed $value 商品ID
- * @param array $data 包含用户ID和购买数量的数组
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- // 从 args 获取参数键名
- $userIdKey = $this->args[0] ?? 'user_id';
- $numberKey = $this->args[1] ?? 'number';
- $shopItemKey = $this->args[2] ?? 'shop_item';
- $userId = $data[$userIdKey] ?? null;
- $number = $data[$numberKey] ?? null;
- $shopItem = $this->validation->$shopItemKey ?? null;
- if (!$userId || !$number || !$shopItem) {
- $this->addError('验证资金时缺少必要参数');
- return false;
- }
- try {
- // 计算总价
- $totalPrice = $shopItem->price * $number;
- // 获取用户账户余额
- $userAccount = AccountService::getUserAccount($userId, $shopItem->currency_id);
-
- if (!$userAccount) {
- $this->addError('用户账户不存在');
- return false;
- }
- if ($userAccount->balance < $totalPrice) {
- $this->addError('余额不足,需要' . $totalPrice . ',当前余额' . $userAccount->balance);
- return false;
- }
- return true;
- } catch (\Exception $e) {
- $this->addError('验证资金时发生错误: ' . $e->getMessage());
- return false;
- }
- }
- }
|