PaperNaming.php 2.3 KB

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