| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- <?php
- namespace App\Http\Controllers\Api;
- use App\Http\Controllers\Controller;
- use App\Models\Question;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\Request;
- class QuestionRandomController extends Controller
- {
- public function __invoke(Request $request): JsonResponse
- {
- $limit = max(1, min(50, (int) $request->input('limit', 10)));
- $query = Question::query();
- if ($kpCode = $request->string('kp_code')->toString()) {
- $query->where('kp_code', $kpCode);
- }
- if ($type = $request->string('question_type')->toString()) {
- $query->where('question_type', $type);
- }
- $stageGrade = $this->normalizeStageGrade((int) $request->input('grade'));
- if ($stageGrade !== null) {
- $query->where('grade', $stageGrade);
- }
- $questions = $query->inRandomOrder()->limit($limit)->get();
- return response()->json([
- 'count' => $questions->count(),
- 'data' => $questions,
- ]);
- }
- private function normalizeStageGrade(int $grade): ?int
- {
- if ($grade <= 0) {
- return null;
- }
- return $grade <= 9 ? 2 : 3;
- }
- }
|