ExamPdfExportService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Controllers\ExamPdfController;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Models\Student;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\File;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Storage;
  11. use Illuminate\Support\Facades\URL;
  12. use App\Services\LearningAnalyticsService;
  13. use App\Services\QuestionBankService;
  14. use App\Services\QuestionServiceApi;
  15. use Symfony\Component\Process\Exception\ProcessSignaledException;
  16. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  17. use Symfony\Component\Process\Process;
  18. class ExamPdfExportService
  19. {
  20. private ExamPdfController $controller;
  21. private LearningAnalyticsService $learningAnalyticsService;
  22. private QuestionBankService $questionBankService;
  23. public function __construct(
  24. ExamPdfController $controller,
  25. LearningAnalyticsService $learningAnalyticsService,
  26. QuestionBankService $questionBankService
  27. )
  28. {
  29. $this->controller = $controller;
  30. $this->learningAnalyticsService = $learningAnalyticsService;
  31. $this->questionBankService = $questionBankService;
  32. }
  33. /**
  34. 生成试卷 PDF(不含答案)
  35. */
  36. public function generateExamPdf(string $paperId): ?string
  37. {
  38. return $this->renderAndStore($paperId, includeAnswer: false, suffix: 'exam');
  39. }
  40. /**
  41. 生成判卷 PDF(含答案与解析)
  42. */
  43. public function generateGradingPdf(string $paperId): ?string
  44. {
  45. return $this->renderAndStore($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  46. }
  47. /**
  48. * 生成学情分析 PDF
  49. */
  50. public function generateAnalysisReportPdf(string $paperId, string $studentId): ?string
  51. {
  52. if (function_exists('set_time_limit')) {
  53. @set_time_limit(240);
  54. }
  55. try {
  56. $payload = $this->buildAnalysisPayload($paperId, $studentId);
  57. if (!$payload) {
  58. return null;
  59. }
  60. $html = view('exam-analysis.pdf-report', $payload)->render();
  61. $pdfBinary = $this->buildPdf($html);
  62. if (!$pdfBinary) {
  63. return null;
  64. }
  65. $version = time();
  66. $path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
  67. Storage::disk('public')->put($path, $pdfBinary);
  68. return URL::to(Storage::url($path));
  69. } catch (\Throwable $e) {
  70. Log::error('ExamPdfExportService: 生成学情分析 PDF 失败', [
  71. 'paper_id' => $paperId,
  72. 'student_id' => $studentId,
  73. 'error' => $e->getMessage(),
  74. 'exception' => get_class($e),
  75. 'trace' => $e->getTraceAsString(),
  76. ]);
  77. return null;
  78. }
  79. }
  80. private function renderAndStore(
  81. string $paperId,
  82. bool $includeAnswer,
  83. string $suffix,
  84. bool $useGradingView = false
  85. ): ?string {
  86. // 放宽脚本执行时间,避免长耗时渲染被 PHP 全局超时打断
  87. if (function_exists('set_time_limit')) {
  88. @set_time_limit(240);
  89. }
  90. try {
  91. $html = $this->renderHtml($paperId, $includeAnswer, $useGradingView);
  92. if (!$html) {
  93. Log::error('ExamPdfExportService: 渲染 HTML 为空', [
  94. 'paper_id' => $paperId,
  95. 'include_answer' => $includeAnswer,
  96. 'use_grading_view' => $useGradingView,
  97. ]);
  98. return null;
  99. }
  100. $pdfBinary = $this->buildPdf($html);
  101. if (!$pdfBinary) {
  102. return null;
  103. }
  104. $path = "exams/{$paperId}_{$suffix}.pdf";
  105. Storage::disk('public')->put($path, $pdfBinary);
  106. return URL::to(Storage::url($path));
  107. } catch (\Throwable $e) {
  108. Log::error('ExamPdfExportService: 生成 PDF 失败', [
  109. 'paper_id' => $paperId,
  110. 'suffix' => $suffix,
  111. 'error' => $e->getMessage(),
  112. 'exception' => get_class($e),
  113. 'trace' => $e->getTraceAsString(),
  114. ]);
  115. return null;
  116. }
  117. }
  118. private function renderHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  119. {
  120. // 复用已有控制器的渲染逻辑,保证版式一致
  121. $request = Request::create(
  122. '/admin/intelligent-exam/' . ($useGradingView ? 'grading' : 'pdf') . '/' . $paperId,
  123. 'GET',
  124. ['answer' => $includeAnswer ? 'true' : 'false']
  125. );
  126. $view = $useGradingView
  127. ? $this->controller->showGrading($request, $paperId)
  128. : $this->controller->show($request, $paperId);
  129. if (is_object($view) && method_exists($view, 'render')) {
  130. return $this->ensureUtf8Html($view->render());
  131. }
  132. return null;
  133. }
  134. private function buildPdf(string $html): ?string
  135. {
  136. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  137. $utf8Html = $this->ensureUtf8Html($html);
  138. file_put_contents($tmpHtml, $utf8Html);
  139. // 仅使用 Chrome 渲染,去掉 wkhtmltopdf 兜底以暴露真实问题
  140. $chromePdf = $this->renderWithChrome($tmpHtml);
  141. @unlink($tmpHtml);
  142. return $chromePdf;
  143. }
  144. private function renderWithChrome(string $htmlPath): ?string
  145. {
  146. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  147. // 固定用户目录,减少 Chrome 首次初始化开销;允许多进程并发时可按需加锁
  148. $userDataDir = sys_get_temp_dir() . '/chrome-pdf-profile';
  149. $chromeBinary = env('PDF_CHROME_BINARY');
  150. if (!$chromeBinary) {
  151. $candidates = [
  152. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  153. '/usr/bin/google-chrome-stable',
  154. '/usr/bin/google-chrome',
  155. '/usr/bin/chromium-browser',
  156. '/usr/bin/chromium',
  157. ];
  158. foreach ($candidates as $path) {
  159. if (is_file($path) && is_executable($path)) {
  160. $chromeBinary = $path;
  161. break;
  162. }
  163. }
  164. }
  165. if (!$chromeBinary) {
  166. Log::error('ExamPdfExportService: 未找到可用的 Chrome/Chromium,已停止导出', [
  167. 'html_path' => $htmlPath,
  168. 'path_env' => env('PATH'),
  169. 'candidates_checked' => $candidates ?? [],
  170. ]);
  171. return null;
  172. }
  173. // 为无权限环境设置可写的 HOME/XDG 目录,避免创建 /var/www/.local 报错
  174. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  175. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  176. if (!File::exists($runtimeHome)) {
  177. @File::makeDirectory($runtimeHome, 0755, true);
  178. }
  179. if (!File::exists($runtimeXdg)) {
  180. @File::makeDirectory($runtimeXdg, 0755, true);
  181. }
  182. $process = new Process([
  183. $chromeBinary,
  184. '--headless',
  185. '--disable-gpu',
  186. '--no-sandbox',
  187. '--disable-setuid-sandbox',
  188. '--disable-dev-shm-usage',
  189. '--no-zygote',
  190. '--disable-features=VizDisplayCompositor',
  191. '--disable-software-rasterizer',
  192. '--disable-extensions',
  193. '--disable-background-networking',
  194. '--disable-component-update',
  195. '--disable-client-side-phishing-detection',
  196. '--disable-default-apps',
  197. '--disable-domain-reliability',
  198. '--disable-sync',
  199. '--safebrowsing-disable-auto-update',
  200. '--no-first-run',
  201. '--no-default-browser-check',
  202. '--disable-crash-reporter',
  203. '--disable-print-preview',
  204. '--disable-features=PrintHeaderFooter',
  205. '--user-data-dir=' . $userDataDir,
  206. '--print-to-pdf=' . $tmpPdf,
  207. '--print-to-pdf-no-header',
  208. '--allow-file-access-from-files',
  209. 'file://' . $htmlPath,
  210. ], null, [
  211. 'HOME' => $runtimeHome,
  212. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  213. ]);
  214. $process->setTimeout(60);
  215. $killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
  216. try {
  217. $startedAt = microtime(true);
  218. Log::info('ExamPdfExportService: Chrome 渲染启动', [
  219. 'cmd' => $process->getCommandLine(),
  220. 'html_path' => $htmlPath,
  221. 'tmp_pdf' => $tmpPdf,
  222. 'user_data_dir' => $userDataDir,
  223. 'html_exists' => file_exists($htmlPath),
  224. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : null,
  225. 'cwd' => $process->getWorkingDirectory(),
  226. ]);
  227. $process->start();
  228. $pdfGenerated = false;
  229. // 轮询检测 PDF 是否生成,尽快返回,避免等待 Chrome 完整退出
  230. $pollStart = microtime(true);
  231. $maxPollSeconds = 45;
  232. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  233. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  234. $pdfGenerated = true;
  235. Log::info('ExamPdfExportService: 发现 PDF 已生成,提前结束 Chrome', [
  236. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  237. 'tmp_pdf_size' => filesize($tmpPdf),
  238. ]);
  239. $process->stop(5, $killSignal);
  240. break;
  241. }
  242. usleep(200_000); // 200ms
  243. }
  244. // 如果仍在运行且超过轮询窗口,则强制结束
  245. if ($process->isRunning()) {
  246. Log::warning('ExamPdfExportService: Chrome 轮询超时,强制结束', [
  247. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  248. ]);
  249. $process->stop(5, $killSignal);
  250. }
  251. $process->wait();
  252. Log::info('ExamPdfExportService: Chrome 渲染完成', [
  253. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  254. 'exit_code' => $process->getExitCode(),
  255. 'tmp_pdf_exists' => file_exists($tmpPdf),
  256. 'tmp_pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : null,
  257. 'stderr' => $process->getErrorOutput(),
  258. 'stdout' => $process->getOutput(),
  259. 'pdf_generated_during_poll' => $pdfGenerated,
  260. ]);
  261. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  262. Log::error('ExamPdfExportService: Chrome 进程异常', [
  263. 'cmd' => $process->getCommandLine(),
  264. 'signal' => method_exists($process, 'getTermSignal') ? $process->getTermSignal() : null,
  265. 'error' => $process->getErrorOutput(),
  266. 'output' => $process->getOutput(),
  267. 'exit_code' => $process->getExitCode(),
  268. 'exception' => $e->getMessage(),
  269. 'trace' => $e->getTraceAsString(),
  270. ]);
  271. if ($process->isRunning()) {
  272. $process->stop(5, $killSignal);
  273. }
  274. $pdfExists = file_exists($tmpPdf);
  275. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  276. if ($pdfExists && $pdfSize > 0) {
  277. Log::warning('ExamPdfExportService: Chrome 异常但产生了 PDF,尝试继续返回', [
  278. 'tmp_pdf_exists' => $pdfExists,
  279. 'tmp_pdf_size' => $pdfSize,
  280. 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
  281. ]);
  282. $pdfBinary = file_get_contents($tmpPdf);
  283. @unlink($tmpPdf);
  284. File::deleteDirectory($userDataDir);
  285. return $pdfBinary ?: null;
  286. }
  287. @unlink($tmpPdf);
  288. File::deleteDirectory($userDataDir);
  289. return null;
  290. } catch (\Throwable $e) {
  291. Log::error('ExamPdfExportService: Chrome 调用异常', [
  292. 'cmd' => $process->getCommandLine(),
  293. 'error' => $e->getMessage(),
  294. 'exit_code' => $process->getExitCode(),
  295. 'stderr' => $process->getErrorOutput(),
  296. 'stdout' => $process->getOutput(),
  297. 'trace' => $e->getTraceAsString(),
  298. ]);
  299. if ($process->isRunning()) {
  300. $process->stop(5, $killSignal);
  301. }
  302. $pdfExists = file_exists($tmpPdf);
  303. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  304. if ($pdfExists && $pdfSize > 0) {
  305. Log::warning('ExamPdfExportService: Chrome 调用异常但产生了 PDF,尝试继续返回', [
  306. 'tmp_pdf_exists' => $pdfExists,
  307. 'tmp_pdf_size' => $pdfSize,
  308. 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
  309. ]);
  310. $pdfBinary = file_get_contents($tmpPdf);
  311. @unlink($tmpPdf);
  312. File::deleteDirectory($userDataDir);
  313. return $pdfBinary ?: null;
  314. }
  315. @unlink($tmpPdf);
  316. File::deleteDirectory($userDataDir);
  317. return null;
  318. }
  319. $pdfExists = file_exists($tmpPdf);
  320. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  321. if (!$process->isSuccessful()) {
  322. if ($pdfExists && $pdfSize > 0) {
  323. Log::warning('ExamPdfExportService: Chrome 进程异常但生成了 PDF,继续使用', [
  324. 'cmd' => implode(' ', (array) $process->getCommandLine()),
  325. 'exit_code' => $process->getExitCode(),
  326. 'error' => $process->getErrorOutput(),
  327. 'output' => $process->getOutput(),
  328. 'tmp_pdf_exists' => $pdfExists,
  329. 'tmp_pdf_size' => $pdfSize,
  330. 'html_path' => $htmlPath,
  331. 'user_data_dir' => $userDataDir,
  332. ]);
  333. } else {
  334. Log::error('ExamPdfExportService: Chrome 渲染失败', [
  335. 'cmd' => implode(' ', (array) $process->getCommandLine()),
  336. 'exit_code' => $process->getExitCode(),
  337. 'error' => $process->getErrorOutput(),
  338. 'output' => $process->getOutput(),
  339. 'tmp_pdf_exists' => $pdfExists,
  340. 'tmp_pdf_size' => $pdfSize,
  341. 'html_path' => $htmlPath,
  342. 'user_data_dir' => $userDataDir,
  343. ]);
  344. @unlink($tmpPdf);
  345. File::deleteDirectory($userDataDir);
  346. return null;
  347. }
  348. }
  349. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  350. @unlink($tmpPdf);
  351. File::deleteDirectory($userDataDir);
  352. return $pdfBinary ?: null;
  353. }
  354. private function buildAnalysisPayload(string $paperId, string $studentId): ?array
  355. {
  356. $paper = Paper::with(['questions' => function ($query) {
  357. $query->orderBy('question_number')->orderBy('id');
  358. }])->find($paperId);
  359. if (!$paper) {
  360. Log::error('ExamPdfExportService: 未找到试卷,无法生成学情报告', [
  361. 'paper_id' => $paperId,
  362. 'student_id' => $studentId,
  363. ]);
  364. return null;
  365. }
  366. $student = Student::find($studentId);
  367. $studentInfo = [
  368. 'id' => $student?->student_id ?? $studentId,
  369. 'name' => $student?->name ?? $studentId,
  370. 'grade' => $student?->grade ?? '未知年级',
  371. 'class' => $student?->class_name ?? '未知班级',
  372. ];
  373. // 调用学习分析服务获取本卷分析与掌握度
  374. $analysisData = [];
  375. if (!empty($paper->analysis_id)) {
  376. $analysis = $this->learningAnalyticsService->getAnalysisResult($paper->analysis_id);
  377. if (!empty($analysis['data'])) {
  378. $analysisData = $analysis['data'];
  379. }
  380. }
  381. $masteryData = [];
  382. $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
  383. if (!empty($masteryResponse['data'])) {
  384. $masteryData = $masteryResponse['data'];
  385. }
  386. $recommendations = [];
  387. $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
  388. if (!empty($recommendationResponse['data'])) {
  389. $recommendations = $recommendationResponse['data'];
  390. }
  391. $kpNameMap = $this->buildKnowledgePointNameMap();
  392. // 预取题库详情用于解析/解题思路
  393. $questionDetails = [];
  394. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  395. foreach ($questionIds as $qid) {
  396. try {
  397. $detail = $this->questionBankService->getQuestion((string) $qid);
  398. if (!empty($detail)) {
  399. $questionDetails[(string) $qid] = $detail;
  400. }
  401. } catch (\Throwable $e) {
  402. Log::warning('ExamPdfExportService: 获取题库题目详情失败', [
  403. 'question_id' => $qid,
  404. 'error' => $e->getMessage(),
  405. ]);
  406. }
  407. }
  408. // 分组保持卷面顺序:选择题 -> 填空题 -> 解答题
  409. $grouped = [
  410. 'choice' => [],
  411. 'fill' => [],
  412. 'answer' => [],
  413. ];
  414. $sortedQuestions = $paper->questions
  415. ->sortBy(function (PaperQuestion $q, int $idx) {
  416. $number = $q->question_number ?? $idx + 1;
  417. return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
  418. });
  419. foreach ($sortedQuestions as $idx => $question) {
  420. $kpCode = $question->knowledge_point ?? '';
  421. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  422. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  423. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  424. // 题型优先使用试卷记录,其次题库详情
  425. $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
  426. $normalizedType = $this->normalizeQuestionType($typeRaw);
  427. $number = $question->question_number ?? ($idx + 1);
  428. $payload = [
  429. 'question_number' => $number,
  430. 'question_text' => is_array($question->question_text) ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE) : ($question->question_text ?? ''),
  431. 'question_type' => $normalizedType,
  432. 'knowledge_point' => $kpCode,
  433. 'knowledge_point_name' => $kpName,
  434. 'score' => $question->score,
  435. 'solution' => $solution,
  436. ];
  437. $grouped[$normalizedType][] = $payload;
  438. }
  439. $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
  440. // 按卷面顺序重新编号以匹配判卷/显示
  441. foreach ($ordered as $i => &$q) {
  442. $q['display_number'] = $i + 1;
  443. }
  444. unset($q);
  445. $questions = $ordered;
  446. $questionInsights = $analysisData['question_results'] ?? [];
  447. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  448. return [
  449. 'paper' => [
  450. 'id' => $paper->paper_id,
  451. 'name' => $paper->paper_name,
  452. 'total_questions' => $paper->question_count,
  453. 'total_score' => $paper->total_score,
  454. 'created_at' => $paper->created_at,
  455. ],
  456. 'student' => $studentInfo,
  457. 'questions' => $questions,
  458. 'mastery' => $masterySummary,
  459. 'question_insights' => $questionInsights,
  460. 'recommendations' => $recommendations,
  461. 'analysis_data' => $analysisData,
  462. ];
  463. }
  464. private function buildKnowledgePointNameMap(): array
  465. {
  466. try {
  467. // 优先使用 QuestionServiceApi(已有知识点名称缓存)
  468. if (class_exists(QuestionServiceApi::class)) {
  469. /** @var QuestionServiceApi $service */
  470. $service = app(QuestionServiceApi::class);
  471. $options = $service->getKnowledgePointOptions();
  472. if (!empty($options)) {
  473. return $options;
  474. }
  475. }
  476. // 退回 QuestionBankService(可能缺少此方法)
  477. if (method_exists($this->questionBankService, 'getKnowledgePointOptions')) {
  478. $options = $this->questionBankService->getKnowledgePointOptions();
  479. $map = [];
  480. foreach ($options as $item) {
  481. if (is_array($item)) {
  482. $code = $item['kp_code'] ?? null;
  483. $name = $item['kp_name'] ?? $item['name'] ?? null;
  484. if ($code && $name) {
  485. $map[$code] = $name;
  486. }
  487. }
  488. }
  489. if (!empty($map)) {
  490. return $map;
  491. }
  492. }
  493. } catch (\Throwable $e) {
  494. Log::warning('ExamPdfExportService: 获取知识点名称失败,退回使用编码', [
  495. 'error' => $e->getMessage(),
  496. ]);
  497. }
  498. return [];
  499. }
  500. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  501. {
  502. $items = [];
  503. $total = 0;
  504. $count = 0;
  505. $hasMap = !empty($kpNameMap);
  506. foreach ($masteryData as $row) {
  507. $code = $row['kp_code'] ?? null;
  508. if ($hasMap && $code && !isset($kpNameMap[$code])) {
  509. // 不在知识图谱中的知识点不呈现
  510. continue;
  511. }
  512. $name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
  513. $level = (float) ($row['mastery_level'] ?? 0);
  514. $delta = $row['mastery_change'] ?? null;
  515. $items[] = [
  516. 'kp_code' => $code,
  517. 'kp_name' => $name,
  518. 'mastery_level' => $level,
  519. 'mastery_change' => $delta,
  520. ];
  521. $total += $level;
  522. $count++;
  523. }
  524. $average = $count > 0 ? round($total / $count, 2) : null;
  525. // 按掌握度从低到高排序,便于突出薄弱点
  526. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  527. return [
  528. 'items' => $items,
  529. 'average' => $average,
  530. 'weak_list' => array_slice($items, 0, 5),
  531. ];
  532. }
  533. private function normalizeQuestionType(?string $type): string
  534. {
  535. $t = strtolower(trim((string) $type));
  536. return match (true) {
  537. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  538. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  539. default => 'answer',
  540. };
  541. }
  542. private function ensureUtf8Html(string $html): string
  543. {
  544. $meta = '<meta charset="UTF-8">';
  545. if (stripos($html, '<head>') !== false) {
  546. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  547. }
  548. return $meta . $html;
  549. }
  550. }