Example #1
0
 /**
  * Starts a quiz by loading its first question
  *
  * @param \Drupal\quiz\QuizInterface $quiz
  * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
  *  Returns a redirect for the first question if questions exist
  *  else it returns a redirect back to quiz.
  */
 public function takeQuiz(QuizInterface $quiz)
 {
     // Only attempt quiz if it has questions.
     $attemptCount = $quiz->get('attempts')->value;
     if ($attemptCount > 0) {
         $statuses = $quiz->getStatuses($this->currentUser());
         if (count($statuses) >= $attemptCount) {
             $status = $quiz->getActiveStatus($this->currentUser());
             if ($status == NULL) {
                 drupal_set_message($this->t('Maximum attempts for this quiz reached.'), 'warning');
                 return $this->redirect('entity.quiz.canonical', ['quiz' => $quiz->id()]);
             }
         }
     }
     $questions = $quiz->getQuestions();
     if (count($questions) != 0) {
         $status = $quiz->getActiveStatus($this->currentUser());
         // If no open quiz session is found, create one.
         if ($status == NULL) {
             $status = UserQuizStatus::create(array());
             $status->setQuiz($quiz);
             $status->setFinished(0);
             $status->setAnswerCount(0);
             $status->save();
         }
         $next = 0;
         $nextQuestion = NULL;
         // Take questions in order mechanism. Extend here to implement random order.
         foreach ($questions as $question) {
             /* @var $question \Drupal\quiz\Entity\Question */
             if ($status->getLastQuestionId() == NULL || $next) {
                 $nextQuestion = $question;
                 break;
             }
             if ($status->getLastQuestionId() == $question->id()) {
                 $next = 1;
             }
         }
         // There is a question to be answered case.
         if ($nextQuestion != NULL) {
             $status->setCurrentQuestion($nextQuestion);
             $status->save();
             return $this->redirect('entity.answer.add_answer', ['question' => $nextQuestion->id()]);
         } elseif ($status->isFinished() == 0) {
             $status->setScore($status->evaluate());
             $status->setMaxScore($quiz->getMaxScore());
             $status->setPercent($quiz->get('percent')->value);
             $status->setQuestionsCount(count($quiz->getQuestions()));
             $status->setFinished(time());
             $status->setCurrentQuestion();
             $status->save();
         }
         return $this->redirect('entity.quiz.canonical', ['quiz' => $quiz->id()]);
     }
     drupal_set_message($this->t('This quiz has no questions.'), 'warning');
     return $this->redirect('entity.quiz.canonical', ['quiz' => $quiz->id()]);
 }