QuestionSearchController.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Question;
  5. use Illuminate\Http\JsonResponse;
  6. use Illuminate\Http\Request;
  7. class QuestionSearchController extends Controller
  8. {
  9. public function __invoke(Request $request): JsonResponse
  10. {
  11. $query = Question::query();
  12. if ($search = $request->string('q')->toString()) {
  13. $query->search($search);
  14. }
  15. if ($kpCode = $request->string('kp_code')->toString()) {
  16. $query->where('kp_code', $kpCode);
  17. }
  18. if ($type = $request->string('question_type')->toString()) {
  19. $query->where('question_type', $type);
  20. }
  21. $stageGrade = $this->normalizeStageGrade((int) $request->input('grade'));
  22. if ($stageGrade !== null) {
  23. $query->where('grade', $stageGrade);
  24. }
  25. $min = $request->float('difficulty_min');
  26. $max = $request->float('difficulty_max');
  27. if ($min !== null && $max !== null) {
  28. $query->whereBetween('difficulty', [$min, $max]);
  29. }
  30. $perPage = max(1, min(50, (int) $request->input('per_page', 20)));
  31. return response()->json($query->paginate($perPage));
  32. }
  33. private function normalizeStageGrade(int $grade): ?int
  34. {
  35. if ($grade <= 0) {
  36. return null;
  37. }
  38. return $grade <= 9 ? 2 : 3;
  39. }
  40. }