| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- namespace App\Services;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- class QuestionDifficultyResolver
- {
- private const TABLE = 'question_difficulty_calibrations';
- private ?bool $tableReady = null;
- /**
- * @param array<int, int|string> $questionIds
- * @return array<int, float> question_bank_id => calibrated_difficulty
- */
- public function mapCalibratedDifficulty(array $questionIds): array
- {
- if (! $this->isReady()) {
- return [];
- }
- $questionIds = collect($questionIds)
- ->map(fn ($id) => (int) $id)
- ->filter(fn ($id) => $id > 0)
- ->unique()
- ->values()
- ->all();
- if ($questionIds === []) {
- return [];
- }
- return DB::table(self::TABLE)
- ->whereIn('question_bank_id', $questionIds)
- ->pluck('calibrated_difficulty', 'question_bank_id')
- ->map(fn ($v) => (float) $v)
- ->all();
- }
- /**
- * 批量给题目数组覆盖 difficulty(校准值优先,原始值兜底)
- *
- * @param array<int, array<string, mixed>> $questions
- * @return array<int, array<string, mixed>>
- */
- public function applyCalibratedDifficulty(array $questions): array
- {
- if ($questions === []) {
- return $questions;
- }
- $ids = [];
- foreach ($questions as $q) {
- $id = (int) ($q['id'] ?? $q['question_id'] ?? $q['question_bank_id'] ?? 0);
- if ($id > 0) {
- $ids[] = $id;
- }
- }
- $map = $this->mapCalibratedDifficulty($ids);
- if ($map === []) {
- return $questions;
- }
- foreach ($questions as &$q) {
- $id = (int) ($q['id'] ?? $q['question_id'] ?? $q['question_bank_id'] ?? 0);
- if ($id > 0 && array_key_exists($id, $map)) {
- $q['difficulty'] = (float) $map[$id];
- $q['difficulty_source'] = 'calibrated';
- }
- }
- unset($q);
- return $questions;
- }
- private function isReady(): bool
- {
- if ($this->tableReady !== null) {
- return $this->tableReady;
- }
- $this->tableReady = Schema::hasTable(self::TABLE);
- return $this->tableReady;
- }
- }
|