MexPriceValidator.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace App\Module\Mex\Validators;
  3. use App\Module\Mex\Services\MexPriceConfigService;
  4. use UCore\Validator;
  5. use Illuminate\Support\Facades\Log;
  6. /**
  7. * 农贸市场价格验证器
  8. *
  9. * 验证交易价格是否在允许的范围内
  10. */
  11. class MexPriceValidator extends Validator
  12. {
  13. /**
  14. * 验证价格是否在合理范围内
  15. *
  16. * @param mixed $value 价格
  17. * @param array $data 所有数据
  18. * @return bool 验证是否通过
  19. */
  20. public function validate(mixed $value, array $data): bool
  21. {
  22. $price = (float)$value;
  23. // 从 args 获取物品ID字段名
  24. $itemIdKey = $this->args[0] ?? 'itemId';
  25. $itemId = $data[$itemIdKey] ?? null;
  26. if (!$itemId) {
  27. $this->addError('物品ID不能为空');
  28. return false;
  29. }
  30. try {
  31. // 获取物品价格配置
  32. $priceConfig = MexPriceConfigService::getItemPriceConfig($itemId);
  33. if (!$priceConfig) {
  34. $this->addError('未找到物品价格配置');
  35. return false;
  36. }
  37. // 验证价格是否在允许范围内
  38. if (!$this->validatePriceRange($price, $priceConfig)) {
  39. return false;
  40. }
  41. // 验证价格精度
  42. if (!$this->validatePricePrecision($price)) {
  43. return false;
  44. }
  45. return true;
  46. } catch (\Exception $e) {
  47. Log::error('农贸市场价格验证失败', [
  48. 'item_id' => $itemId,
  49. 'price' => $price,
  50. 'error' => $e->getMessage()
  51. ]);
  52. $this->addError('价格验证时发生错误');
  53. return false;
  54. }
  55. }
  56. /**
  57. * 验证价格是否在允许范围内
  58. *
  59. * @param float $price 价格
  60. * @param array $priceConfig 价格配置
  61. * @return bool
  62. */
  63. private function validatePriceRange(float $price, array $priceConfig): bool
  64. {
  65. $minPrice = (float)$priceConfig['min_price'];
  66. $maxPrice = (float)$priceConfig['max_price'];
  67. if ($price < $minPrice) {
  68. $this->addError("价格不能低于 {$minPrice}");
  69. return false;
  70. }
  71. if ($price > $maxPrice) {
  72. $this->addError("价格不能高于 {$maxPrice}");
  73. return false;
  74. }
  75. return true;
  76. }
  77. /**
  78. * 验证价格精度
  79. *
  80. * @param float $price 价格
  81. * @return bool
  82. */
  83. private function validatePricePrecision(float $price): bool
  84. {
  85. // 检查小数位数是否超过5位
  86. $priceStr = (string)$price;
  87. if (strpos($priceStr, '.') !== false) {
  88. $decimalPart = substr($priceStr, strpos($priceStr, '.') + 1);
  89. if (strlen($decimalPart) > 5) {
  90. $this->addError('价格小数位数不能超过5位');
  91. return false;
  92. }
  93. }
  94. return true;
  95. }
  96. }