You are here

function QuizController::resume in Quiz 8.6

Same name and namespace in other branches
  1. 8.5 src/Controller/QuizController.php \Drupal\quiz\Controller\QuizController::resume()
  2. 6.x src/Controller/QuizController.php \Drupal\quiz\Controller\QuizController::resume()

Resume a quiz.

Search the database for an in progress attempt, and put it back into the session if allowed.

Return value

QuizResult

1 call to QuizController::resume()
QuizController::take in src/Controller/QuizController.php
Take the quiz.

File

src/Controller/QuizController.php, line 155

Class

QuizController

Namespace

Drupal\quiz\Controller

Code

function resume($quiz) {
  $user = \Drupal::currentUser();

  // Make sure we use the same revision of the quiz throughout the quiz taking
  // session.
  $result_id = !empty($_SESSION['quiz'][$quiz
    ->id()]['result_id']) ? $_SESSION['quiz'][$quiz
    ->id()]['result_id'] : NULL;
  if ($result_id && ($quiz_result = QuizResult::load($result_id))) {
    return $quiz_result;
  }
  else {

    // User doesn't have attempt in session. If we allow resuming we can load it
    // from the database.
    if ($quiz
      ->get('allow_resume')
      ->getString() && $user
      ->isAuthenticated()) {
      if ($quiz_result = $quiz
        ->getResumeableResult($user)) {

        // Put the result in the user's session.
        $_SESSION['quiz'][$quiz
          ->id()]['result_id'] = $quiz_result
          ->id();
        $_SESSION['quiz'][$quiz
          ->id()]['current'] = 1;

        // Now advance the user to after the last answered question.
        $prev = NULL;
        foreach ($quiz_result
          ->getLayout() as $qra) {
          if ($prev) {
            if ($qra
              ->get('answer_timestamp')
              ->isEmpty() && !$prev
              ->get('answer_timestamp')
              ->isEmpty()) {

              // This question has not been answered, but the previous
              // question has.
              $_SESSION['quiz'][$quiz
                ->id()]['current'] = $qra
                ->get('number')
                ->getString();
            }
          }
          $prev = clone $qra;
        }

        // Mark this quiz as being resumed from the database.
        $quiz_result->resume = TRUE;
        return $quiz_result;
      }
    }
  }
  return FALSE;
}