42 lines
1.5 KiB
PHP
42 lines
1.5 KiB
PHP
<?php
|
||
|
||
namespace App\Support\CourierBills;
|
||
|
||
final class Waybill
|
||
{
|
||
/**
|
||
* 单号规范化:去空白、前导 @ 和撇号、末尾 .0。
|
||
*
|
||
* 科学计数法要分两种:xlsx 数字单元格里存的是完整值(如 7.9150812345678E+13,有效位够),
|
||
* 可以还原;文本或 CSV 里的「7.91508E+13」是 Excel 显示截断后的值,末几位已经丢了,必须拒收。
|
||
*
|
||
* @return array{waybill:?string,reason:?string}
|
||
*/
|
||
public static function parse(string $value): array
|
||
{
|
||
$text = preg_replace('/\s+/u', '', $value) ?? '';
|
||
$text = ltrim($text, "@''`");
|
||
if (preg_match('/^(\d+)\.0+$/', $text, $m)) {
|
||
$text = $m[1];
|
||
}
|
||
if (preg_match('/^(\d)(?:\.(\d+))?E\+?(\d+)$/i', $text, $m)) {
|
||
$fraction = $m[2] ?? '';
|
||
$exponent = (int) $m[3];
|
||
if (strlen($fraction) + 1 < 12 || strlen($fraction) > $exponent) {
|
||
return ['waybill' => null, 'reason' => '单号是科学计数法,已被 Excel 截断'];
|
||
}
|
||
$text = $m[1] . str_pad($fraction, $exponent, '0');
|
||
}
|
||
if (! preg_match('/^[A-Za-z0-9-]{4,96}$/', $text)) {
|
||
return ['waybill' => null, 'reason' => '单号格式不对'];
|
||
}
|
||
|
||
return ['waybill' => strtoupper($text), 'reason' => null];
|
||
}
|
||
|
||
public static function normalize(?string $value): ?string
|
||
{
|
||
return self::parse((string) $value)['waybill'];
|
||
}
|
||
}
|