You are here

function template_preprocess_opigno_user_result_item in Opigno module 3.x

Same name and namespace in other branches
  1. 8 opigno_module.module \template_preprocess_opigno_user_result_item()

User result item preprocess template.

File

./opigno_module.module, line 110
Contains opigno_module.module.

Code

function template_preprocess_opigno_user_result_item(&$variables) {
  $route = \Drupal::routeMatch();

  /** @var \Drupal\opigno_module\Entity\OpignoModule $opigno_module */
  $opigno_module = $route
    ->getParameter('opigno_module');

  /** @var \Drupal\opigno_module\Entity\OpignoAnswer $answer */
  $answer = $variables['opigno_answer'];

  // Check if module allow display answer content for users.
  $hide_results = $opigno_module
    ->getHideResults($answer);

  /** @var Drupal\opigno_module\Entity\OpignoActivity $answer_activity */
  $answer_activity = $variables['opigno_answer_activity'];

  /* @var $answer_service \Drupal\opigno_module\ActivityAnswerManager */
  $answer_service = \Drupal::service('plugin.manager.activity_answer');
  $answer_activity_type = $answer_activity
    ->getType();
  if (!$hide_results) {

    // Get the data about an answer.
    if ($answer_service
      ->hasDefinition($answer_activity_type)) {
      $answer_instance = $answer_service
        ->createInstance($answer_activity_type);
      $headings = $answer_instance
        ->getAnswerResultItemHeaders($answer);
      $result_data = $answer_instance
        ->getAnswerResultItemData($answer);
      if (!empty($result_data)) {
        $content = [
          '#theme' => 'table',
          '#header' => $headings,
          '#rows' => $result_data,
        ];
        $variables['content'] = $content;
      }
    }

    // Output question body field.
    if ($answer_activity
      ->hasField('opigno_body')) {
      $viewBuilder = \Drupal::entityTypeManager()
        ->getViewBuilder('opigno_activity');
      $variables['question_body'] = $viewBuilder
        ->viewField($answer_activity
        ->get('opigno_body'), 'full');
    }
  }

  // Output question number info.
  if ($variables['question_number']) {
    $activity_title = $answer_activity
      ->getName();
    $variables['label'] = $variables['question_number'] . '. ' . ucfirst($activity_title);
  }
  if (isset($variables['answer_max_score']) && $variables['answer_max_score'] > 0) {

    // Get the user score.
    $variables['score'] = t('Score: %score of %max_score', [
      '%score' => $answer
        ->isEvaluated() ? $answer
        ->getScore() : '?',
      '%max_score' => $variables['answer_max_score'],
    ]);
  }
  else {
    $variables['score'] = t('No score retrieved');
  }
  $variables['#attached']['library'][] = 'opigno_module/module_results_page';
}