machineId; $existingBatchNo = EctActionsRepository::new()->findTodayActiveBatchNo($machineId); $datePart = date('Ymd'); $sequence = 1; if (!empty($existingBatchNo)) { $existingDatePart = substr($existingBatchNo, 0, 8); $existingSequence = substr($existingBatchNo, 10, 4); if ($existingDatePart === $datePart && is_numeric($existingSequence)) { $sequence = (int)$existingSequence + 1; } } $sequencePart = str_pad($sequence, 4, '0', STR_PAD_LEFT); return new self(value: $datePart . $machineId . $sequencePart); } /** * 解析批次号结构 * * @return array{date: string, machineId: string, sequence: int, dateFormatted: string} */ public function parse(): array { if (!$this->isValid()) { return [ 'date' => '', 'machineId' => '', 'sequence' => 0, 'dateFormatted' => '', ]; } $datePart = substr($this->value, 0, 8); $machineId = substr($this->value, 8, 2); $sequence = (int)substr($this->value, 10, 4); return [ 'date' => $datePart, 'machineId' => $machineId, 'sequence' => $sequence, 'dateFormatted' => substr($datePart, 0, 4) . '-' . substr($datePart, 4, 2) . '-' . substr($datePart, 6, 2), ]; } /** * 解析批次号结构 * @deprecated * @return array{date: string, machineId: string, sequence: int, dateFormatted: string} */ public static function parseBatchNo(string $batchNo): array { $batch = BatchNo::fromString($batchNo); if (!$batch->isValid()) { throw new \InvalidArgumentException('Invalid batch string: ' . $batchNo); } return $batch->parse(); } /** * 验证批次号格式是否有效 */ public function isValid(): bool { // 批次号格式: YYYYMMDD + 机器ID(2位) + 序号(4位) = 14位 if (strlen($this->value) !== 14) { return false; } $datePart = substr($this->value, 0, 8); $sequencePart = substr($this->value, 10, 4); // 验证日期部分 if (!is_numeric($datePart)) { return false; } // 验证序号部分 if (!is_numeric($sequencePart)) { return false; } return true; } /** * 是否为空批次号 */ public function isEmpty(): bool { return empty($this->value); } /** * 获取日期部分 */ public function getDateStr(): string { $parsed = $this->parse(); return $parsed['dateFormatted']; } /** * 获取时间戳 * @return int|false */ public function getTimestamp(): int|false { $parsed = $this->parse(); return strtotime($parsed['dateFormatted']); } /** * 获取机器ID */ public function getMachineId(): string { $parsed = $this->parse(); return $parsed['machineId']; } /** * 获取序号 */ public function getSequence(): int { $parsed = $this->parse(); return $parsed['sequence']; } /** * 是否是今天的批次号 */ public function isToday(): bool { if (!$this->isValid()) { return false; } $datePart = substr($this->value, 0, 8); return $datePart === date('Ymd'); } /** * 转换为字符串 */ public function __toString(): string { return $this->value; } }