You are here

function QuizResult::copyToQuizResult in Quiz 6.x

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

Copy this result's answers onto another Quiz result, based on the new Quiz result's settings.

Parameters

QuizResult $result_new: An empty QuizResult.

File

src/Entity/QuizResult.php, line 607

Class

QuizResult
Defines the Quiz entity class.

Namespace

Drupal\quiz\Entity

Code

function copyToQuizResult(QuizResult $result_new) {

  // Re-take all the questions.
  foreach ($this
    ->getLayout() as $qra) {
    if (($result_new->build_on_last == 'all' || $qra
      ->isCorrect()) && !$qra
      ->isSkipped()) {

      // Populate answer.
      $duplicate = $qra
        ->createDuplicate();
      $duplicate
        ->set('uuid', \Drupal::service('uuid')
        ->generate());
    }
    else {

      // Create new answer.
      $duplicate = QuizResultAnswer::create([
        'type' => $qra
          ->bundle(),
      ]);
      foreach ($qra
        ->getFields() as $name => $field) {

        /* @var $field Drupal\Core\Field\FieldItemList */
        if (!in_array($name, [
          'result_answer_id',
          'uuid',
        ]) && is_a($field
          ->getFieldDefinition(), '\\Drupal\\Core\\Field\\BaseFieldDefinition')) {

          // Copy any base fields, but not the answer.
          $duplicate
            ->set($name, $field
            ->getValue());
        }
      }
    }

    // Set new result ID.
    $duplicate
      ->set('result_id', $result_new
      ->id());
    $duplicate
      ->save();
  }
}