PaperNaming.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. 15 => '错题再练',
  16. 16 => '错题追练',
  17. 22 => '知识点讲解',
  18. default => throw new InvalidArgumentException("不支持的 assemble_type: {$assembleType}"),
  19. };
  20. }
  21. public static function extractExamCode(string $paperId): string
  22. {
  23. preg_match('/paper_(\d{15})/', $paperId, $matches);
  24. $examCode = $matches[1] ?? '';
  25. if ($examCode === '') {
  26. $digits = preg_replace('/[^0-9]/', '', $paperId);
  27. $examCode = substr(str_pad($digits, 15, '0', STR_PAD_LEFT), -15);
  28. }
  29. if (!PaperIdGenerator::validate($examCode)) {
  30. throw new InvalidArgumentException("无效的考试编码: {$paperId}");
  31. }
  32. return $examCode !== '' ? $examCode : $paperId;
  33. }
  34. public static function buildPaperDisplayTitle(string $studentName, string $paperId, int $assembleType): string
  35. {
  36. $prefix = self::buildPaperPrefix($studentName, $paperId, $assembleType);
  37. $date = now()->format('Ymd');
  38. return "{$prefix}_{$date}";
  39. }
  40. public static function buildPaperPrefix(string $studentName, string $paperId, int $assembleType): string
  41. {
  42. $examCode = self::extractExamCode($paperId);
  43. $label = self::assembleTypeLabel($assembleType);
  44. return "{$studentName}_{$examCode}_{$label}";
  45. }
  46. public static function buildPaperDisplayTitleWithStamp(string $studentName, string $paperId, int $assembleType, string $stamp): string
  47. {
  48. $prefix = self::buildPaperPrefix($studentName, $paperId, $assembleType);
  49. return "{$prefix}_{$stamp}";
  50. }
  51. public static function buildPdfTitle(string $studentName, string $paperId, int $assembleType, string $kind): string
  52. {
  53. return self::buildPaperDisplayTitle($studentName, $paperId, $assembleType)."_{$kind}";
  54. }
  55. public static function toSafeFilename(string $name, int $maxLength = 120): string
  56. {
  57. $safe = preg_replace('/[\\\\\\/\\:\\*\\?\\\"\\<\\>\\|\\s]+/u', '_', trim($name));
  58. $safe = preg_replace('/_+/u', '_', (string) $safe);
  59. $safe = trim((string) $safe, '._');
  60. if ($safe === '') {
  61. $safe = 'paper';
  62. }
  63. if (mb_strlen($safe) > $maxLength) {
  64. $safe = mb_substr($safe, 0, $maxLength);
  65. }
  66. return $safe;
  67. }
  68. }