| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace App\Module\Mex\Validators;
- use App\Module\Mex\Services\MexPriceConfigService;
- use UCore\Validator;
- use Illuminate\Support\Facades\Log;
- /**
- * 农贸市场价格验证器
- *
- * 验证交易价格是否在允许的范围内
- */
- class MexPriceValidator extends Validator
- {
- /**
- * 验证价格是否在合理范围内
- *
- * @param mixed $value 价格
- * @param array $data 所有数据
- * @return bool 验证是否通过
- */
- public function validate(mixed $value, array $data): bool
- {
- $price = (float)$value;
-
- // 从 args 获取物品ID字段名
- $itemIdKey = $this->args[0] ?? 'itemId';
- $itemId = $data[$itemIdKey] ?? null;
- if (!$itemId) {
- $this->addError('物品ID不能为空');
- return false;
- }
- try {
- // 获取物品价格配置
- $priceConfig = MexPriceConfigService::getItemPriceConfig($itemId);
-
- if (!$priceConfig) {
- $this->addError('未找到物品价格配置');
- return false;
- }
- // 验证价格是否在允许范围内
- if (!$this->validatePriceRange($price, $priceConfig)) {
- return false;
- }
- // 验证价格精度
- if (!$this->validatePricePrecision($price)) {
- return false;
- }
- return true;
- } catch (\Exception $e) {
- Log::error('农贸市场价格验证失败', [
- 'item_id' => $itemId,
- 'price' => $price,
- 'error' => $e->getMessage()
- ]);
-
- $this->addError('价格验证时发生错误');
- return false;
- }
- }
- /**
- * 验证价格是否在允许范围内
- *
- * @param float $price 价格
- * @param array $priceConfig 价格配置
- * @return bool
- */
- private function validatePriceRange(float $price, array $priceConfig): bool
- {
- $minPrice = (float)$priceConfig['min_price'];
- $maxPrice = (float)$priceConfig['max_price'];
- if ($price < $minPrice) {
- $this->addError("价格不能低于 {$minPrice}");
- return false;
- }
- if ($price > $maxPrice) {
- $this->addError("价格不能高于 {$maxPrice}");
- return false;
- }
- return true;
- }
- /**
- * 验证价格精度
- *
- * @param float $price 价格
- * @return bool
- */
- private function validatePricePrecision(float $price): bool
- {
- // 检查小数位数是否超过5位
- $priceStr = (string)$price;
-
- if (strpos($priceStr, '.') !== false) {
- $decimalPart = substr($priceStr, strpos($priceStr, '.') + 1);
-
- if (strlen($decimalPart) > 5) {
- $this->addError('价格小数位数不能超过5位');
- return false;
- }
- }
- return true;
- }
- }
|