$definition) { if ($definition['type'] !== 'number' || ! isset($input[$field])) { continue; } $number = str_replace([',', ',', '¥', '¥'], '', trim((string) $input[$field])); if (preg_match('/^-?(?:\d+)?\.\d{5,}$/', $number) !== 1) { continue; } // 全程十进制运算,不把金额或大整数转成 float。 $magnitude = ltrim($number, '-'); $scale = strlen(explode('.', $number, 2)[1]); $rounded = bcadd($magnitude, '0.00005', 4); $difference = ltrim(bcsub($magnitude, $rounded, $scale), '-'); if (bccomp($difference, '0.000000000001', max(12, $scale)) <= 0) { $input[$field] = str_starts_with($number, '-') && bccomp($rounded, '0', 4) !== 0 ? '-' . $rounded : $rounded; } } return $this->normalize($fields, $input); } /** @param array $fields */ public function normalize(array $fields, array $input): array { $values = []; foreach ($fields as $field => $definition) { if (! array_key_exists($field, $input)) { continue; } $value = $input[$field]; if ($value === null || trim((string) $value) === '') { $values[$field] = null; continue; } if ($definition['type'] === 'number') { $number = str_replace([',', ',', '¥', '¥'], '', trim((string) $value)); if (preg_match('/^-?(?:\d+(?:\.\d{1,4})?|\.\d{1,4})$/', $number) !== 1 || bccomp(ltrim($number, '-'), '9999999999999999.9999', 4) === 1) { throw ValidationException::withMessages([ $field => $definition['label'] . '必须是最多 4 位小数的有效数字。', ]); } $values[$field] = $number; continue; } $text = trim((string) $value); if (mb_strlen($text) > 5000) { throw ValidationException::withMessages([$field => $definition['label'] . '内容过长。']); } if ($definition['type'] === 'date' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $text) !== 1) { throw ValidationException::withMessages([$field => $definition['label'] . '日期格式无效。']); } if ($definition['type'] === 'month' && preg_match('/^\d{4}-\d{2}$/', $text) !== 1) { throw ValidationException::withMessages([$field => $definition['label'] . '月份格式无效。']); } $values[$field] = $text; } if ($values === []) { throw ValidationException::withMessages(['values' => '没有可保存的字段。']); } return $values; } }