You are here

function Quiz::getRandomQuestions in Quiz 6.x

Same name and namespace in other branches
  1. 8.6 src/Entity/Quiz.php \Drupal\quiz\Entity\Quiz::getRandomQuestions()
  2. 8.5 src/Entity/Quiz.php \Drupal\quiz\Entity\Quiz::getRandomQuestions()

Get random questions for a quiz.

Return value

array Array questions.

1 call to Quiz::getRandomQuestions()
Quiz::buildLayout in src/Entity/Quiz.php
Retrieves a list of questions (to be taken) for a given quiz.

File

src/Entity/Quiz.php, line 819

Class

Quiz
Defines the Quiz entity class.

Namespace

Drupal\quiz\Entity

Code

function getRandomQuestions() {
  $num_random = $this
    ->get('number_of_random_questions')
    ->getString();
  $questions = [];
  if ($num_random > 0) {

    // Select random question from assigned pool.
    $query = Drupal::entityQuery('quiz_question_relationship');
    $query
      ->condition('quiz_vid', $this
      ->getRevisionId());
    $query
      ->condition('question_status', QuizQuestion::QUESTION_RANDOM);
    $query
      ->addTag('quiz_random');
    $query
      ->range(0, $this
      ->get('number_of_random_questions')
      ->getString());
    if ($relationships = $query
      ->execute()) {

      /* @var $qqrs QuizQuestionRelationship[] */
      $qqrs = QuizQuestionRelationship::loadMultiple($relationships);
      foreach ($qqrs as $qqr) {
        $questionEntity = Drupal::entityTypeManager()
          ->getStorage('quiz_question')
          ->loadRevision($qqr
          ->get('question_vid')
          ->getString());
        $question = [
          'qqid' => $questionEntity
            ->id(),
          'vid' => $questionEntity
            ->getRevisionId(),
          'type' => $questionEntity
            ->bundle(),
          'random' => TRUE,
          'relative_max_score' => $this
            ->get('max_score_for_random')
            ->getString(),
        ];
        $questions[] = $question;
      }
      return $questions;
    }
  }
  return [];
}