You are here

public function MatchingResponse::score in Quiz 8.5

Same name and namespace in other branches
  1. 8.6 question_types/quiz_matching/src/Plugin/quiz/QuizQuestion/MatchingResponse.php \Drupal\quiz_matching\Plugin\quiz\QuizQuestion\MatchingResponse::score()
  2. 6.x question_types/quiz_matching/src/Plugin/quiz/QuizQuestion/MatchingResponse.php \Drupal\quiz_matching\Plugin\quiz\QuizQuestion\MatchingResponse::score()

Implementation of score().

Overrides QuizResultAnswerEntityTrait::score

See also

QuizQuestionResponse::score()

File

question_types/quiz_matching/src/Plugin/quiz/QuizQuestion/MatchingResponse.php, line 22

Class

MatchingResponse
Extension of QuizQuestionResponse

Namespace

Drupal\quiz_matching\Plugin\quiz\QuizQuestion

Code

public function score(array $values) {

  // Reset whatever was here already.
  $this
    ->get('matching_user_answer')
    ->setValue(NULL);
  foreach ($this
    ->getQuizQuestion()
    ->get('quiz_matching')
    ->referencedEntities() as $paragraph) {

    //foreach ($values['answer']['user_answer'] as $left_id => $right_id) {
    $left_paragraph = $paragraph;
    $right_paragraph = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->loadRevision($values['answer']['user_answer'][$paragraph
      ->getRevisionId()]);
    $new_paragraph = \Drupal\paragraphs\Entity\Paragraph::create([
      'type' => 'quiz_matching_answer',
      'matching_user_question' => $left_paragraph,
      'matching_user_answer' => $right_paragraph,
    ]);
    $this
      ->get('matching_user_answer')
      ->appendItem($new_paragraph);
  }
  $answers = $this
    ->getQuizQuestion()
    ->getCorrectAnswer();
  foreach ($this
    ->get('matching_user_answer')
    ->referencedEntities() as $pair) {
    if ($pair
      ->get('matching_user_answer')
      ->getValue()) {
      $response[$pair
        ->get('matching_user_question')
        ->getValue()[0]['target_revision_id']] = $pair
        ->get('matching_user_answer')
        ->getValue()[0]['target_revision_id'];
    }
    else {
      $response[$pair
        ->get('matching_user_question')
        ->getValue()[0]['target_revision_id']] = -1;
    }
  }
  $score = 0;
  foreach ($answers as $vid => $answer) {
    if ($response[$vid] == $vid) {
      $score++;
    }
    elseif ($response[$vid] != -1 && $this
      ->getQuizQuestion()
      ->get('choice_penalty')
      ->getString()) {
      $score -= 1;
    }
  }
  return $score > 0 ? $score : 0;
}