You are here

class QuizResultViewBuilder in Quiz 6.x

Same name and namespace in other branches
  1. 8.6 src/View/QuizResultViewBuilder.php \Drupal\quiz\View\QuizResultViewBuilder
  2. 8.5 src/View/QuizResultViewBuilder.php \Drupal\quiz\View\QuizResultViewBuilder

Hierarchy

Expanded class hierarchy of QuizResultViewBuilder

File

src/View/QuizResultViewBuilder.php, line 19

Namespace

Drupal\quiz\View
View source
class QuizResultViewBuilder extends EntityViewBuilder {
  use MessengerTrait;
  public function alterBuild(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

    /* @var $entity QuizResult */
    $render_controller = Drupal::entityTypeManager()
      ->getViewBuilder('quiz_result_answer');
    if ($entity
      ->get('is_invalid')->value && \Drupal::currentUser()
      ->id() == $entity
      ->get('uid')
      ->getString()) {
      \Drupal::messenger()
        ->addWarning(t('Your previous score on this @quiz was equal or better. This result will not be saved.', [
        '@quiz' => QuizUtil::getQuizName(),
      ]));
    }
    if (!$entity->is_evaluated && empty($_POST)) {
      $msg = t('Parts of this @quiz have not been evaluated yet. The score below is not final.', [
        '@quiz' => QuizUtil::getQuizName(),
      ]);
      $this
        ->messenger()
        ->addWarning($msg);
    }
    $score = $entity
      ->score();
    $account = User::load($entity
      ->get('uid')
      ->getString());
    if ($display
      ->getComponent('questions')) {
      $questions = [];
      foreach ($entity
        ->getLayout() as $qra) {

        // Loop through all the questions and get their feedback.
        $question = Drupal::entityTypeManager()
          ->getStorage('quiz_question')
          ->loadRevision($qra
          ->get('question_vid')
          ->getString());
        if (!$question) {

          // Question went missing...
          continue;
        }
        if ($question
          ->hasFeedback() && $entity
          ->hasReview()) {
          $feedback = $render_controller
            ->view($qra);
          $feedback_rendered = \Drupal::service('renderer')
            ->renderRoot($feedback);
          if ($feedback_rendered) {
            $questions[$question
              ->id()] = [
              '#title' => t('Question @num', [
                '@num' => $qra
                  ->get('display_number')
                  ->getString(),
              ]),
              '#type' => 'fieldset',
              'feedback' => [
                '#markup' => $feedback_rendered,
              ],
              '#weight' => $qra
                ->get('number')
                ->getString(),
            ];
          }
        }
      }
      if ($questions) {
        $build['questions'] = $questions;
      }
    }
    $quiz_feedback['#children'] = '';
    if ($display
      ->getComponent('summary') && $entity
      ->canReview('quiz_feedback')) {
      $summary = $this
        ->getSummaryText($entity);

      // Show quiz feedback.
      if (!empty($summary['passfail'])) {
        $quiz_feedback['#children'] .= '<div id="quiz-summary">' . $summary['passfail'] . '</div>';
      }
      if (!empty($summary['result'])) {
        $quiz_feedback['#children'] .= '<div id="quiz-summary">' . $summary['result'] . '</div>';
      }
    }
    if ($quiz_feedback['#children']) {
      $build['summary']['#children'] = $quiz_feedback['#children'];
    }
    if ($display
      ->getComponent('score') && $entity
      ->canReview('score')) {
      $params = [
        '%num_correct' => $score['numeric_score'],
        '%question_count' => $score['possible_score'],
        '@username' => $account
          ->id() == \Drupal::currentUser()
          ->id() ? t('You') : $account
          ->getDisplayName(),
        '@score' => $score['percentage_score'],
        '@yourtotal' => $account
          ->id() == \Drupal::currentUser()
          ->id() ? t('Your') : t('Total'),
      ];

      // Show score.
      $build['score']['#markup'] = '<div id="quiz_score_possible">' . t('@username got %num_correct of %question_count possible points.', $params) . '</div>' . "\n";
      $build['score']['#markup'] .= '<div id="quiz_score_percent">' . t('@yourtotal score: @score%', $params) . '</div>';
    }
    if (!Element::children($build)) {
      $build['no_feedback_text']['#markup'] = t('You have finished this @quiz.', [
        '@quiz' => QuizUtil::getQuizName(),
      ]);
    }

    // The visibility of feedback may change based on time or other conditions.
    $build['#cache']['max-age'] = 0;
    return $build;
  }

  /**
   * Get the summary message for a completed quiz result.
   *
   * Summary is determined by the pass/fail configurations on the quiz.
   *
   * @param QuizResult $quiz_result
   *   The quiz result.
   *
   * @return
   *   Render array.
   */
  function getSummaryText(QuizResult $quiz_result) {
    $config = Drupal::config('quiz.settings');
    $quiz = Drupal::entityTypeManager()
      ->getStorage('quiz')
      ->loadRevision($quiz_result
      ->get('vid')
      ->getString());
    $token = Drupal::token();
    $account = $quiz_result
      ->get('uid')
      ->referencedEntities()[0];
    $token_types = [
      'global' => NULL,
      'node' => $quiz,
      'user' => $account,
      'quiz_result' => $quiz_result,
    ];
    $summary = [];
    if ($paragraph = $this
      ->getRangeFeedback($quiz, $quiz_result
      ->get('score')
      ->getString())) {

      // Found quiz feedback based on a grade range.
      $token = Drupal::token();
      $paragraph_text = $paragraph
        ->get('quiz_feedback')
        ->get(0)
        ->getValue();
      $summary['result'] = check_markup($token
        ->replace($paragraph_text['value'], $token_types), $paragraph_text['format']);
    }
    $pass_text = $quiz
      ->get('summary_pass')
      ->getValue()[0];
    $default_text = $quiz
      ->get('summary_default')
      ->getValue()[0];
    if ($config
      ->get('use_passfail', 1) && $quiz
      ->get('pass_rate')
      ->getString() > 0) {
      if ($quiz_result
        ->get('score')
        ->getString() >= $quiz
        ->get('pass_rate')
        ->getString()) {

        // Pass/fail is enabled and user passed.
        $summary['passfail'] = check_markup($token
          ->replace($pass_text['value'], $token_types), $pass_text['format']);
      }
      else {

        // User failed.
        $summary['passfail'] = check_markup($token
          ->replace($default_text['value'], $token_types), $default_text['format']);
      }
    }
    else {

      // Pass/fail is not being used so display the default.
      $summary['passfail'] = check_markup($token
        ->replace($default_text['value'], $token_types), $default_text['format']);
    }
    return $summary;
  }

  /**
   * Get summary text for a particular score from a set of result options.
   *
   * @param Quiz $quiz
   *   The quiz.
   * @param int $score
   *   The percentage score.
   *
   * @return Paragraph
   */
  function getRangeFeedback($quiz, $score) {
    foreach ($quiz
      ->get('result_options')
      ->referencedEntities() as $paragraph) {
      $range = $paragraph
        ->get('quiz_feedback_range')
        ->get(0)
        ->getValue();
      if ($score >= $range['from'] && $score <= $range['to']) {
        return $paragraph;
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 5
EntityHandlerBase::moduleHandler protected function Gets the module handler. 5
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
EntityViewBuilder::$cacheBin protected property The cache bin used to store the render cache.
EntityViewBuilder::$entityDisplayRepository protected property The entity display repository.
EntityViewBuilder::$entityRepository protected property The entity repository service.
EntityViewBuilder::$entityType protected property Information about the entity type.
EntityViewBuilder::$entityTypeId protected property The type of entities for which this view builder is instantiated.
EntityViewBuilder::$languageManager protected property The language manager.
EntityViewBuilder::$singleFieldDisplays protected property The EntityViewDisplay objects created for individual field rendering.
EntityViewBuilder::$themeRegistry protected property The theme registry.
EntityViewBuilder::addContextualLinks protected function Add contextual links.
EntityViewBuilder::build public function Builds an entity's view; augments entity defaults.
EntityViewBuilder::buildComponents public function Builds the component fields and properties of a set of entities. Overrides EntityViewBuilderInterface::buildComponents 7
EntityViewBuilder::buildMultiple public function Builds multiple entities' views; augments entity defaults.
EntityViewBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityHandlerInterface::createInstance 3
EntityViewBuilder::getBuildDefaults protected function Provides entity-specific defaults to the build process. 4
EntityViewBuilder::getCacheTags public function The cache tag associated with this entity view builder. Overrides EntityViewBuilderInterface::getCacheTags
EntityViewBuilder::getSingleFieldDisplay protected function Gets an EntityViewDisplay for rendering an individual field.
EntityViewBuilder::isViewModeCacheable protected function Determines whether the view mode is cacheable.
EntityViewBuilder::resetCache public function Resets the entity render cache. Overrides EntityViewBuilderInterface::resetCache
EntityViewBuilder::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 2
EntityViewBuilder::view public function Builds the render array for the provided entity. Overrides EntityViewBuilderInterface::view 4
EntityViewBuilder::viewField public function Builds a renderable array for the value of a single field in an entity. Overrides EntityViewBuilderInterface::viewField
EntityViewBuilder::viewFieldItem public function Builds a renderable array for a single field item. Overrides EntityViewBuilderInterface::viewFieldItem
EntityViewBuilder::viewMultiple public function Builds the render array for the provided entities. Overrides EntityViewBuilderInterface::viewMultiple 4
EntityViewBuilder::__construct public function Constructs a new EntityViewBuilder. 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
QuizResultViewBuilder::alterBuild public function Specific per-entity building. Overrides EntityViewBuilder::alterBuild
QuizResultViewBuilder::getRangeFeedback function Get summary text for a particular score from a set of result options.
QuizResultViewBuilder::getSummaryText function Get the summary message for a completed quiz result.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.