PaperNaming.php 2.7 KB

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