QuestionRandomController.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 QuestionRandomController extends Controller
  8. {
  9. public function __invoke(Request $request): JsonResponse
  10. {
  11. $limit = max(1, min(50, (int) $request->input('limit', 10)));
  12. $query = Question::query();
  13. if ($kpCode = $request->string('kp_code')->toString()) {
  14. $query->where('kp_code', $kpCode);
  15. }
  16. if ($type = $request->string('question_type')->toString()) {
  17. $query->where('question_type', $type);
  18. }
  19. $stageGrade = $this->normalizeStageGrade((int) $request->input('grade'));
  20. if ($stageGrade !== null) {
  21. $query->where('grade', $stageGrade);
  22. }
  23. $questions = $query->inRandomOrder()->limit($limit)->get();
  24. return response()->json([
  25. 'count' => $questions->count(),
  26. 'data' => $questions,
  27. ]);
  28. }
  29. private function normalizeStageGrade(int $grade): ?int
  30. {
  31. if ($grade <= 0) {
  32. return null;
  33. }
  34. return $grade <= 9 ? 2 : 3;
  35. }
  36. }