Quiz::submit_question()


Source

File: classes/Quiz.php

	public function submit_question() {
		global $wpdb;

		$user_id    = get_current_user_id();
		$questions  = dozent_input_array_field( 'questions' );
		$attempt_id = dozent_input_text( 'attempt_id' );

		if ( dozent_count( $questions ) ) {

			foreach ( $questions as $question_id => $answer ) {

				$question = dozent_get_question( $question_id );
				$answer   = is_string( $answer ) ? $answer : json_encode( $answer );

				$is_correct = 0;
				$r_score    = 0;

				if ( $question->question_type === 'true_false' ) {
					if ( $question->mixed_value == $answer ) {
						$is_correct = 1;
						$r_score    = $question->score;
					}
				} elseif ( $question->question_type === 'radio' ) {
					$option = dozent_get_question_correct_options( $question_id, true );
					if ( $option && $option->option_id == $answer ) {
						$is_correct = 1;
						$r_score    = $question->score;
					}
				} elseif ( $question->question_type === 'checkbox' ) {
					$options    = (array) dozent_get_question_correct_options( $question_id );
					$option_ids = wp_list_pluck( $options, 'option_id' );

					if ( ! count( array_diff( $option_ids, json_decode( $answer, true ) ) ) ) {
						$is_correct = 1;
						$r_score    = $question->score;
					}
				}

				$answerData = apply_filters( 'dozent_quiz_attempt_answer_data', [
					'quiz_id'       => $question->quiz_id,
					'question_id'   => $question_id,
					'user_id'       => $user_id,
					'attempt_id'    => $attempt_id,
					'answer'        => $answer,
					'q_type'        => $question->question_type,
					'q_score'       => $question->score,
					'earned_scores' => $r_score,
					'is_correct'    => $is_correct,
				] );

				$wpdb->insert( $wpdb->dozent_quiz_answers, $answerData );
			}
		}

		wp_send_json_success( [ 'quiz_url' => get_the_permalink( $question->quiz_id ) ] );
	}