ShopFundValidator.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Module\Shop\Validators;
  3. use App\Module\Fund\Services\AccountService;
  4. use UCore\Validator;
  5. /**
  6. * 商店资金验证器
  7. *
  8. * 验证用户资金是否充足
  9. */
  10. class ShopFundValidator extends Validator
  11. {
  12. /**
  13. * 验证用户资金
  14. *
  15. * @param mixed $value 商品ID
  16. * @param array $data 包含用户ID和购买数量的数组
  17. * @return bool 验证是否通过
  18. */
  19. public function validate(mixed $value, array $data): bool
  20. {
  21. // 从 args 获取参数键名
  22. $userIdKey = $this->args[0] ?? 'user_id';
  23. $numberKey = $this->args[1] ?? 'number';
  24. $shopItemKey = $this->args[2] ?? 'shop_item';
  25. $userId = $data[$userIdKey] ?? null;
  26. $number = $data[$numberKey] ?? null;
  27. $shopItem = $this->validation->$shopItemKey ?? null;
  28. if (!$userId || !$number || !$shopItem) {
  29. $this->addError('验证资金时缺少必要参数');
  30. return false;
  31. }
  32. try {
  33. // 计算总价
  34. $totalPrice = $shopItem->price * $number;
  35. // 获取用户账户余额
  36. $userAccount = AccountService::getUserAccount($userId, $shopItem->currency_id);
  37. if (!$userAccount) {
  38. $this->addError('用户账户不存在');
  39. return false;
  40. }
  41. if ($userAccount->balance < $totalPrice) {
  42. $this->addError('余额不足,需要' . $totalPrice . ',当前余额' . $userAccount->balance);
  43. return false;
  44. }
  45. return true;
  46. } catch (\Exception $e) {
  47. $this->addError('验证资金时发生错误: ' . $e->getMessage());
  48. return false;
  49. }
  50. }
  51. }