PaperNaming.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Support;
  3. use App\Services\PaperIdGenerator;
  4. use InvalidArgumentException;
  5. class PaperNaming
  6. {
  7. public static function assembleTypeLabel(int $assembleType): string
  8. {
  9. return match ($assembleType) {
  10. 0, 9 => '智能摸底',
  11. 1, 4, 8 => '智能组题',
  12. 2 => '知识点组题',
  13. 3 => '教材组题',
  14. 5 => '智能追练',
  15. default => throw new InvalidArgumentException("不支持的 assemble_type: {$assembleType}"),
  16. };
  17. }
  18. public static function extractExamCode(string $paperId): string
  19. {
  20. preg_match('/paper_(\d{15})/', $paperId, $matches);
  21. $examCode = $matches[1] ?? '';
  22. if ($examCode === '') {
  23. $digits = preg_replace('/[^0-9]/', '', $paperId);
  24. $examCode = substr(str_pad($digits, 15, '0', STR_PAD_LEFT), -15);
  25. }
  26. if (!PaperIdGenerator::validate($examCode)) {
  27. throw new InvalidArgumentException("无效的考试编码: {$paperId}");
  28. }
  29. return $examCode !== '' ? $examCode : $paperId;
  30. }
  31. public static function buildPaperDisplayTitle(string $studentName, string $paperId, int $assembleType): string
  32. {
  33. $prefix = self::buildPaperPrefix($studentName, $paperId, $assembleType);
  34. $date = now()->format('Ymd');
  35. return "{$prefix}_{$date}";
  36. }
  37. public static function buildPaperPrefix(string $studentName, string $paperId, int $assembleType): string
  38. {
  39. $examCode = self::extractExamCode($paperId);
  40. $label = self::assembleTypeLabel($assembleType);
  41. return "{$studentName}_{$examCode}_{$label}";
  42. }
  43. public static function buildPaperDisplayTitleWithStamp(string $studentName, string $paperId, int $assembleType, string $stamp): string
  44. {
  45. $prefix = self::buildPaperPrefix($studentName, $paperId, $assembleType);
  46. return "{$prefix}_{$stamp}";
  47. }
  48. public static function buildPdfTitle(string $studentName, string $paperId, int $assembleType, string $kind): string
  49. {
  50. return self::buildPaperDisplayTitle($studentName, $paperId, $assembleType)."_{$kind}";
  51. }
  52. public static function toSafeFilename(string $name, int $maxLength = 120): string
  53. {
  54. $safe = preg_replace('/[\\\\\\/\\:\\*\\?\\\"\\<\\>\\|\\s]+/u', '_', trim($name));
  55. $safe = preg_replace('/_+/u', '_', (string) $safe);
  56. $safe = trim((string) $safe, '._');
  57. if ($safe === '') {
  58. $safe = 'paper';
  59. }
  60. if (mb_strlen($safe) > $maxLength) {
  61. $safe = mb_substr($safe, 0, $maxLength);
  62. }
  63. return $safe;
  64. }
  65. }