PaperNaming.php 2.6 KB

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