You are here

class QuizResult in Quiz 6.x

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

Defines the Quiz entity class.

Plugin annotation


@ContentEntityType(
  id = "quiz_result",
  label = @Translation("Quiz result"),
  label_collection = @Translation("Quiz results"),
  label_singular = @Translation("quiz result"),
  label_plural = @Translation("quiz results"),
  label_count = @PluralTranslation(
    singular = "@count quiz result",
    plural = "@count quiz results",
  ),
  bundle_label = @Translation("Quiz result type"),
  bundle_entity_type = "quiz_result_type",
  admin_permission = "administer quiz_result",
  permission_granularity = "entity_type",
  base_table = "quiz_result",
  fieldable = TRUE,
  field_ui_base_route = "entity.quiz_result_type.edit_form",
  show_revision_ui = FALSE,
  entity_keys = {
    "id" = "result_id",
    "published" = "released",
    "owner" = "uid",
    "bundle" = "type",
    "uuid" = "uuid",
  },
  handlers = {
    "view_builder" = "Drupal\quiz\View\QuizResultViewBuilder",
    "access" = "Drupal\quiz\Access\QuizResultAccessControlHandler",
    "permission_provider" = "Drupal\entity\UncacheableEntityPermissionProvider",
    "route_provider" = {
      "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
    },
   "form" = {
      "default" = "Drupal\quiz\Form\QuizResultEntityForm",
      "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
    },
    "views_data" = "Drupal\entity\EntityViewsData",
  },
  links = {
    "canonical" = "/quiz/{quiz}/result/{quiz_result}",
    "edit-form" = "/quiz/{quiz}/result/{quiz_result}/edit",
    "delete-form" = "/quiz/{quiz}/result/{quiz_result}/delete"
  }
)

Hierarchy

Expanded class hierarchy of QuizResult

17 files declare their use of QuizResult
ajax_quiz.module in modules/ajax_quiz/ajax_quiz.module
module file for ajax_quiz quiz module
quiz.module in ./quiz.module
Contains quiz.module
QuizAnswerInterface.php in src/QuizAnswerInterface.php
QuizController.php in src/Controller/QuizController.php
QuizGradingTest.php in tests/src/Functional/QuizGradingTest.php

... See full list

File

src/Entity/QuizResult.php, line 66

Namespace

Drupal\quiz\Entity
View source
class QuizResult extends ContentEntityBase implements EntityOwnerInterface, EntityChangedInterface {
  use EntityOwnerTrait;
  use EntityChangedTrait;

  /**
   * Get the layout for this quiz result.
   *
   * The layout contains the questions to be delivered.
   *
   * @return QuizResultAnswer[]
   */
  public function getLayout() {
    if ($this
      ->isNew()) {

      // New results do not have layouts yet.
      return [];
    }
    $quiz_result_answers = Drupal::entityTypeManager()
      ->getStorage('quiz_result_answer')
      ->loadByProperties([
      'result_id' => $this
        ->id(),
    ]);

    // @todo when we load the layout we have to load the question relationships
    // too because we need to know the parentage
    $quiz_question_relationship = Drupal::entityTypeManager()
      ->getStorage('quiz_question_relationship')
      ->loadByProperties([
      'quiz_vid' => $this
        ->get('vid')
        ->getString(),
    ]);
    $id_qqr = [];
    foreach ($quiz_question_relationship as $rel) {
      $id_qqr[$rel
        ->get('question_id')
        ->getString()] = $rel;
    }
    $layout = [];
    foreach ($quiz_result_answers as $quiz_result_answer) {
      $layout[$quiz_result_answer
        ->get('number')
        ->getString()] = $quiz_result_answer;
      $question_id = $quiz_result_answer
        ->get('question_id')
        ->getString();
      if (isset($id_qqr[$question_id])) {

        // Question is in a relationship.
        // @todo better way to do this? We need to load the relationship
        // hierarchy onto the result answers.
        $quiz_result_answer->qqr_id = $id_qqr[$question_id]
          ->get('qqr_id')
          ->getString();
        $quiz_result_answer->qqr_pid = $id_qqr[$question_id]
          ->get('qqr_pid')
          ->getString();
      }
    }
    ksort($layout, SORT_NUMERIC);
    return $layout;
  }

  /**
   * Get the label for this quiz result.
   *
   * @return string
   */
  public function label() {
    $quiz = $this
      ->getQuiz();
    $user = $this
      ->get('uid')
      ->referencedEntities()[0];
    return t('@user\'s @quiz result in "@title"', [
      '@user' => $user
        ->getDisplayName(),
      '@quiz' => QuizUtil::getQuizName(),
      '@title' => $quiz
        ->get('title')
        ->getString(),
    ]);
  }
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);
    $fields['result_id'] = BaseFieldDefinition::create('integer')
      ->setRequired(TRUE)
      ->setLabel('Quiz result ID');
    $fields['qid'] = BaseFieldDefinition::create('entity_reference')
      ->setRequired(TRUE)
      ->setSetting('target_type', 'quiz')
      ->setLabel(t('Quiz'));
    $fields['vid'] = BaseFieldDefinition::create('integer')
      ->setRequired(TRUE)
      ->setLabel('Quiz revision ID');
    $fields['time_start'] = BaseFieldDefinition::create('timestamp')
      ->setLabel('Attempt start time');
    $fields['time_end'] = BaseFieldDefinition::create('timestamp')
      ->setLabel('Attempt end time');
    $fields['released'] = BaseFieldDefinition::create('boolean')
      ->setLabel('Released')
      ->setDefaultValue(0);
    $fields['score'] = BaseFieldDefinition::create('integer')
      ->setLabel('Score');
    $fields['is_invalid'] = BaseFieldDefinition::create('boolean')
      ->setDefaultValue(0)
      ->setLabel('Invalid');
    $fields['is_evaluated'] = BaseFieldDefinition::create('boolean')
      ->setDefaultValue(0)
      ->setLabel('Evaluated');
    $fields['attempt'] = BaseFieldDefinition::create('integer')
      ->setRequired(TRUE)
      ->setDefaultValue(1)
      ->setLabel('Attempt');
    $fields['type'] = BaseFieldDefinition::create('string')
      ->setRequired(TRUE)
      ->setLabel('Result type');
    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel('Created');
    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel('Changed');
    return $fields;
  }

  /**
   * Save the Quiz result and do any post-processing to the result.
   *
   * @param type $this
   * @param \DatabaseTransaction $transaction
   *
   * @return bool
   */
  public function save() {
    if ($this
      ->get('time_start')
      ->isEmpty()) {
      $this
        ->set('time_start', \Drupal::time()
        ->getRequestTime());
    }
    $new = $this
      ->isNew();
    if ($new) {

      // New attempt, we need to set the attempt number if there are previous
      // attempts.
      if ($this
        ->get('uid')
        ->getString() == 0) {

        // If anonymous, the attempt is always 1.
        $this->attempt = 1;
      }
      else {

        // Get the highest attempt number.
        $efq = \Drupal::entityQuery('quiz_result');
        $result = $efq
          ->range(0, 1)
          ->condition('qid', $this
          ->get('qid')
          ->getString())
          ->condition('uid', $this
          ->get('uid')
          ->getString())
          ->sort('attempt', 'DESC')
          ->execute();
        if (!empty($result)) {
          $keys = array_keys($result);
          $existing = QuizResult::load(reset($keys));
          $this
            ->set('attempt', $existing
            ->get('attempt')
            ->getString() + 1);
        }
      }
    }

    // Save the Quiz result.
    if (!$new) {
      $original = \Drupal::entityTypeManager()
        ->getStorage('quiz_result')
        ->loadUnchanged($this
        ->id());
    }
    parent::save();

    // Post process the result.
    if ($new) {
      $quiz = \Drupal::entityTypeManager()
        ->getStorage('quiz')
        ->loadRevision($this
        ->get('vid')
        ->getString());

      // Create question list.
      $questions = $quiz
        ->buildLayout();
      if (empty($questions)) {
        \Drupal::messenger()
          ->addError(t('Not enough questions were found. Please add more questions before trying to take this @quiz.', array(
          '@quiz' => QuizUtil::getQuizName(),
        )));
        return FALSE;
      }
      if (in_array($this->build_on_last, [
        'correct',
        'all',
      ]) && ($quiz_result_old = self::findOldResult($this))) {

        // Build on the last attempt the user took. If this quiz has build on
        // last attempt set, we need to search for a previous attempt with the
        // same version of the current quiz.
        // Now clone the answers on top of the new result.
        $quiz_result_old
          ->copyToQuizResult($this);
      }
      else {
        $i = 0;
        $j = 0;
        foreach ($questions as $question) {
          $quizQuestion = \Drupal::entityTypeManager()
            ->getStorage('quiz_question')
            ->loadRevision($question['vid']);
          $quiz_result_answer = QuizResultAnswer::create([
            'result_id' => $this
              ->id(),
            'question_id' => $question['qqid'],
            'question_vid' => $question['vid'],
            'type' => $quizQuestion
              ->bundle(),
            'tid' => !empty($question['tid']) ? $question['tid'] : NULL,
            'number' => ++$i,
            'display_number' => $quizQuestion
              ->isQuestion() ? ++$j : NULL,
          ]);
          $quiz_result_answer
            ->save();
        }
      }
    }
    if (isset($original) && !$original
      ->get('is_evaluated')->value && $this
      ->get('is_evaluated')->value) {

      // Quiz is finished! Delete old results if necessary.
      $this
        ->maintainResults();
    }
  }
  function getAccount() {
    return $this
      ->get('uid')
      ->referencedEntities()[0];
  }

  /**
   * Mark results as invalid for a quiz according to the keep results setting.
   *
   * This function will only mark the results as invalid. The actual delete
   * action happens based on a cron run.
   * If we would have deleted the results in this function the user might not
   * have been able to view the result screen of the quiz he just finished.
   *
   * @param QuizResult $quiz_result
   *   The result of the latest result for the current user.
   *
   * @return bool
   *   TRUE if results were marked as invalid, FALSE otherwise.
   */
  function maintainResults() {
    $db = \Drupal::database();
    $quiz = $this
      ->getQuiz();
    $user = $this
      ->getAccount();

    // Do not delete results for anonymous users.
    if ($user
      ->id() == 0) {
      return FALSE;
    }
    $result_ids = [];
    switch ((int) $quiz
      ->get('keep_results')
      ->getString()) {
      case Quiz::KEEP_ALL:
        break;
      case Quiz::KEEP_BEST:
        $best_result_id = $db
          ->select('quiz_result', 'qnr')
          ->fields('qnr', [
          'result_id',
        ])
          ->condition('qnr.qid', $quiz
          ->id())
          ->condition('qnr.uid', $user
          ->id())
          ->condition('qnr.is_evaluated', 1)
          ->condition('qnr.is_invalid', 0)
          ->orderBy('score', 'DESC')
          ->execute()
          ->fetchField();
        if ($best_result_id) {
          $result_ids = $db
            ->select('quiz_result', 'qnr')
            ->fields('qnr', [
            'result_id',
          ])
            ->condition('qnr.qid', $quiz
            ->id())
            ->condition('qnr.uid', $user
            ->id())
            ->condition('qnr.is_evaluated', 1)
            ->condition('qnr.is_invalid', 0)
            ->condition('qnr.result_id', $best_result_id, '!=')
            ->execute()
            ->fetchCol('result_id');
        }
        break;
      case Quiz::KEEP_LATEST:
        $result_ids = $db
          ->select('quiz_result', 'qnr')
          ->fields('qnr', [
          'result_id',
        ])
          ->condition('qnr.qid', $quiz
          ->id())
          ->condition('qnr.uid', $user
          ->id())
          ->condition('qnr.is_evaluated', 1)
          ->condition('qnr.is_invalid', 0)
          ->condition('qnr.result_id', $this
          ->id(), '!=')
          ->execute()
          ->fetchCol('result_id');
        break;
    }
    if ($result_ids) {
      $db
        ->update('quiz_result')
        ->fields([
        'is_invalid' => 1,
      ])
        ->condition('result_id', $result_ids, 'IN')
        ->execute();
      return TRUE;
    }
    return FALSE;
  }

  /**
   * Update the session for this quiz to the active question.
   *
   * @param int $question_number
   *   Question number starting at 1.
   */
  function setQuestion($question_number) {

    /* @var $quiz_session \Drupal\quiz\Services\QuizSessionInterface */
    $quiz_session = \Drupal::service('quiz.session');
    $quiz = $this
      ->getQuiz();
    $quiz_session
      ->setCurrentQuestion($quiz, $question_number);
  }

  /**
   * Can the quiz taker view the requested review?
   *
   * There's a workaround in here: @kludge
   *
   * When review for the question is enabled, and it is the last question,
   * technically it is the end of the quiz, and the "end of quiz" review
   * settings apply. So we check to make sure that we are in question taking
   * and the feedback is viewed within 5 seconds of completing the
   * question/quiz.
   *
   * @param string $option
   *   An option key.
   * @param QuizResult $quiz_result
   *   A Quiz result.
   *
   * @return bool
   *   TRUE if the quiz taker can view this quiz option at this time, FALSE
   *   otherwise.
   */
  function canReview($option) {
    $config = Drupal::config('quiz.settings');

    // Load quiz associated with this result.
    $quiz = \Drupal::entityTypeManager()
      ->getStorage('quiz')
      ->loadRevision($this
      ->get('vid')
      ->getString());
    $admin = $quiz
      ->access('update');
    if ($config
      ->get('override_admin_feedback') && $admin) {

      // Admin user uses the global feedback options.
      $review_options['end'] = $config
        ->get('admin_review_options_end');
      $review_options['question'] = $config
        ->get('admin_review_options_question');
    }
    else {

      // Use this Quiz's feedback options.
      if ($quiz
        ->get('review_options')
        ->get(0)) {
        $review_options = $quiz
          ->get('review_options')
          ->get(0)
          ->getValue();
      }
      else {
        $review_options = [];
      }
    }

    // Hold combined review options from each feedback type.
    $all_shows = [];
    $rules = \Drupal::moduleHandler()
      ->moduleExists('rules');
    $feedbackTypes = QuizFeedbackType::loadMultiple();
    foreach ($review_options as $time_key => $shows) {

      /* @var $component RulesComponent */
      $component = $feedbackTypes[$time_key]
        ->getComponent();
      $component
        ->setContextValue('quiz_result', $this);
      if ($component
        ->getExpression()
        ->executeWithState($component
        ->getState())) {

        // Add selected feedbacks to the show list.
        $all_shows += array_filter($shows);
      }
    }
    return !empty($all_shows[$option]);
  }

  /**
   * Score a quiz result.
   */
  function finalize() {
    $questions = $this
      ->getLayout();

    // Mark all missing answers as blank. This is essential here for when we may
    // have pages of unanswered questions. Also kills a lot of the skip code that
    // was necessary before.
    foreach ($questions as $qinfo) {

      // If the result answer has not been marked as skipped and it hasn't been
      // answered.
      if (empty($qinfo->is_skipped) && empty($qinfo->answer_timestamp)) {
        $qinfo->is_skipped = 1;
        $qinfo
          ->save();
      }
    }
    $score = $this
      ->score();
    if (!isset($score['percentage_score'])) {
      $score['percentage_score'] = 0;
    }

    // @todo Could be removed if we implement any "released" functionality.
    $this
      ->set('released', 1);
    $this
      ->set('is_evaluated', $score['is_evaluated']);
    $this
      ->set('score', $score['percentage_score']);
    $this
      ->set('time_end', \Drupal::time()
      ->getRequestTime());
    $this
      ->save();
    return $this;
  }

  /**
   * Calculates the score user received on quiz.
   *
   * @param $quiz
   *   The quiz node.
   * @param $result_id
   *   Quiz result ID.
   *
   * @return array
   *   Contains five elements:
   *     - question_count
   *     - possible_score
   *     - numeric_score
   *     - percentage_score
   *     - is_evaluated
   */
  function score() {
    $quiz_result_answers = $this
      ->getLayout();
    $numeric_score = $possible_score = 0;
    $is_evaluated = 1;
    foreach ($quiz_result_answers as $quiz_result_answer) {

      // Get the scaled point value for this question response.
      $numeric_score += $quiz_result_answer
        ->getPoints();

      // Get the scaled max score for this question relationship.
      $possible_score += $quiz_result_answer
        ->getMaxScore();
      if (!$quiz_result_answer
        ->isEvaluated()) {
        $is_evaluated = 0;
      }
    }
    return [
      'question_count' => count($quiz_result_answers),
      'possible_score' => $possible_score,
      'numeric_score' => $numeric_score,
      'percentage_score' => $possible_score == 0 ? 0 : round($numeric_score * 100 / $possible_score),
      'is_evaluated' => $is_evaluated,
    ];
  }

  /**
   * {@inheritdoc}
   *
   * Delete all result answers when a result is deleted.
   */
  public function delete() {
    $entities = \Drupal::entityTypeManager()
      ->getStorage('quiz_result_answer')
      ->loadByProperties([
      'result_id' => $this
        ->id(),
    ]);
    foreach ($entities as $entity) {
      $entity
        ->delete();
    }

    //\Drupal::entityTypeManager()->getStorage('quiz_result_answer')->delete($entities);
    parent::delete();
  }

  /**
   * Find a result that is not the same as the passed result.
   *
   * Note: the Quiz result does not have an actually exist - in that case, it
   * will return the first completed result found.
   *
   * // @todo what?
   * // Oh, this is to find a result for build-on-last.
   */
  public function findOldResult() {
    $efq = \Drupal::entityQuery('quiz_result');
    $result = $efq
      ->condition('uid', $this
      ->get('uid')
      ->getString())
      ->condition('qid', $this
      ->get('qid')
      ->getString())
      ->condition('vid', $this
      ->get('vid')
      ->getString())
      ->condition('result_id', (int) $this
      ->id(), '!=')
      ->condition('time_start', 0, '>')
      ->sort('time_start', 'DESC')
      ->range(0, 1)
      ->execute();
    if (!empty($result)) {
      return QuizResult::load(key($result));
    }
    return NULL;
  }

  /**
   * Can the quiz taker view any reviews right now?
   *
   * @return bool
   */
  public function hasReview() {
    foreach (quiz_get_feedback_options() as $option => $label) {
      if ($this
        ->canReview($option)) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   *
   * Quiz results are never viewed outside of a Quiz, so we enforce that a Quiz
   * route parameter is added.
   */
  public function toUrl($rel = 'canonical', array $options = []) {
    $url = parent::toUrl($rel, $options);
    $url
      ->setRouteParameter('quiz', $this
      ->get('qid')
      ->getString());
    return $url;
  }

  /**
   * Get the Quiz of this result.
   *
   * @return \Drupal\quiz\Entity\Quiz
   */
  public function getQuiz() {
    return Drupal::entityTypeManager()
      ->getStorage('quiz')
      ->loadRevision($this
      ->get('vid')
      ->getString());
  }

  /**
   * Copy this result's answers onto another Quiz result, based on the new Quiz
   * result's settings.
   *
   * @param QuizResult $result_new
   *   An empty QuizResult.
   */
  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();
    }
  }

  /**
   * Determine if the time limit has been reached for this attempt.
   *
   * @return bool
   */
  function isTimeReached() {
    $quiz = $this
      ->getQuiz();
    $config = \Drupal::config('quiz.settings');
    $time_limit = $quiz
      ->get('time_limit')
      ->getString();
    $time_limit_buffer = $config
      ->get('time_limit_buffer', 5);
    $time_start = $this
      ->get('time_start')
      ->getString();
    $request_time = \Drupal::time()
      ->getRequestTime();
    return $time_limit > 0 && $request_time > $time_start + $time_limit + $time_limit_buffer;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
ContentEntityBase::$activeLangcode protected property Language code identifying the entity active language.
ContentEntityBase::$defaultLangcode protected property Local cache for the default language code.
ContentEntityBase::$defaultLangcodeKey protected property The default langcode entity key.
ContentEntityBase::$enforceRevisionTranslationAffected protected property Whether the revision translation affected flag has been enforced.
ContentEntityBase::$entityKeys protected property Holds untranslatable entity keys such as the ID, bundle, and revision ID.
ContentEntityBase::$fieldDefinitions protected property Local cache for field definitions.
ContentEntityBase::$fields protected property The array of fields, each being an instance of FieldItemListInterface.
ContentEntityBase::$fieldsToSkipFromTranslationChangesCheck protected static property Local cache for fields to skip from the checking for translation changes.
ContentEntityBase::$isDefaultRevision protected property Indicates whether this is the default revision.
ContentEntityBase::$langcodeKey protected property The language entity key.
ContentEntityBase::$languages protected property Local cache for the available language objects.
ContentEntityBase::$loadedRevisionId protected property The loaded revision ID before the new revision was set.
ContentEntityBase::$newRevision protected property Boolean indicating whether a new revision should be created on save.
ContentEntityBase::$revisionTranslationAffectedKey protected property The revision translation affected entity key.
ContentEntityBase::$translatableEntityKeys protected property Holds translatable entity keys such as the label.
ContentEntityBase::$translationInitialize protected property A flag indicating whether a translation object is being initialized.
ContentEntityBase::$translations protected property An array of entity translation metadata.
ContentEntityBase::$validated protected property Whether entity validation was performed.
ContentEntityBase::$validationRequired protected property Whether entity validation is required before saving the entity.
ContentEntityBase::$values protected property The plain data values of the contained fields.
ContentEntityBase::access public function Checks data value access. Overrides EntityBase::access 1
ContentEntityBase::addTranslation public function Adds a new translation to the translatable object. Overrides TranslatableInterface::addTranslation
ContentEntityBase::bundle public function Gets the bundle of the entity. Overrides EntityBase::bundle
ContentEntityBase::bundleFieldDefinitions public static function Provides field definitions for a specific bundle. Overrides FieldableEntityInterface::bundleFieldDefinitions 4
ContentEntityBase::clearTranslationCache protected function Clear entity translation object cache to remove stale references.
ContentEntityBase::createDuplicate public function Creates a duplicate of the entity. Overrides EntityBase::createDuplicate 1
ContentEntityBase::get public function Gets a field item list. Overrides FieldableEntityInterface::get
ContentEntityBase::getEntityKey protected function Gets the value of the given entity key, if defined. 1
ContentEntityBase::getFieldDefinition public function Gets the definition of a contained field. Overrides FieldableEntityInterface::getFieldDefinition
ContentEntityBase::getFieldDefinitions public function Gets an array of field definitions of all contained fields. Overrides FieldableEntityInterface::getFieldDefinitions
ContentEntityBase::getFields public function Gets an array of all field item lists. Overrides FieldableEntityInterface::getFields
ContentEntityBase::getFieldsToSkipFromTranslationChangesCheck protected function Returns an array of field names to skip in ::hasTranslationChanges. 1
ContentEntityBase::getIterator public function
ContentEntityBase::getLanguages protected function
ContentEntityBase::getLoadedRevisionId public function Gets the loaded Revision ID of the entity. Overrides RevisionableInterface::getLoadedRevisionId
ContentEntityBase::getRevisionId public function Gets the revision identifier of the entity. Overrides RevisionableInterface::getRevisionId
ContentEntityBase::getTranslatableFields public function Gets an array of field item lists for translatable fields. Overrides FieldableEntityInterface::getTranslatableFields
ContentEntityBase::getTranslatedField protected function Gets a translated field.
ContentEntityBase::getTranslation public function Gets a translation of the data. Overrides TranslatableInterface::getTranslation
ContentEntityBase::getTranslationLanguages public function Returns the languages the data is translated to. Overrides TranslatableInterface::getTranslationLanguages
ContentEntityBase::getTranslationStatus public function Returns the translation status. Overrides TranslationStatusInterface::getTranslationStatus
ContentEntityBase::getUntranslated public function Returns the translatable object referring to the original language. Overrides TranslatableInterface::getUntranslated
ContentEntityBase::hasField public function Determines whether the entity has a field with the given name. Overrides FieldableEntityInterface::hasField
ContentEntityBase::hasTranslation public function Checks there is a translation for the given language code. Overrides TranslatableInterface::hasTranslation
ContentEntityBase::hasTranslationChanges public function Determines if the current translation of the entity has unsaved changes. Overrides TranslatableInterface::hasTranslationChanges
ContentEntityBase::id public function Gets the identifier. Overrides EntityBase::id
ContentEntityBase::initializeTranslation protected function Instantiates a translation object for an existing translation.
ContentEntityBase::isDefaultRevision public function Checks if this entity is the default revision. Overrides RevisionableInterface::isDefaultRevision
ContentEntityBase::isDefaultTranslation public function Checks whether the translation is the default one. Overrides TranslatableInterface::isDefaultTranslation
ContentEntityBase::isDefaultTranslationAffectedOnly public function Checks if untranslatable fields should affect only the default translation. Overrides TranslatableRevisionableInterface::isDefaultTranslationAffectedOnly
ContentEntityBase::isLatestRevision public function Checks if this entity is the latest revision. Overrides RevisionableInterface::isLatestRevision
ContentEntityBase::isLatestTranslationAffectedRevision public function Checks whether this is the latest revision affecting this translation. Overrides TranslatableRevisionableInterface::isLatestTranslationAffectedRevision
ContentEntityBase::isNewRevision public function Determines whether a new revision should be created on save. Overrides RevisionableInterface::isNewRevision
ContentEntityBase::isNewTranslation public function Checks whether the translation is new. Overrides TranslatableInterface::isNewTranslation
ContentEntityBase::isRevisionTranslationAffected public function Checks whether the current translation is affected by the current revision. Overrides TranslatableRevisionableInterface::isRevisionTranslationAffected
ContentEntityBase::isRevisionTranslationAffectedEnforced public function Checks if the revision translation affected flag value has been enforced. Overrides TranslatableRevisionableInterface::isRevisionTranslationAffectedEnforced
ContentEntityBase::isTranslatable public function Returns the translation support status. Overrides TranslatableInterface::isTranslatable
ContentEntityBase::isValidationRequired public function Checks whether entity validation is required before saving the entity. Overrides FieldableEntityInterface::isValidationRequired
ContentEntityBase::language public function Gets the language of the entity. Overrides EntityBase::language
ContentEntityBase::onChange public function Reacts to changes to a field. Overrides FieldableEntityInterface::onChange
ContentEntityBase::postCreate public function Acts on a created entity before hooks are invoked. Overrides EntityBase::postCreate
ContentEntityBase::postSave public function Acts on a saved entity before the insert or update hook is invoked. Overrides EntityBase::postSave 9
ContentEntityBase::preSave public function Acts on an entity before the presave hook is invoked. Overrides EntityBase::preSave 8
ContentEntityBase::preSaveRevision public function Acts on a revision before it gets saved. Overrides RevisionableInterface::preSaveRevision 3
ContentEntityBase::referencedEntities public function Gets a list of entities referenced by this entity. Overrides EntityBase::referencedEntities 1
ContentEntityBase::removeTranslation public function Removes the translation identified by the given language code. Overrides TranslatableInterface::removeTranslation
ContentEntityBase::set public function Sets a field value. Overrides FieldableEntityInterface::set
ContentEntityBase::setDefaultLangcode protected function Populates the local cache for the default language code.
ContentEntityBase::setNewRevision public function Enforces an entity to be saved as a new revision. Overrides RevisionableInterface::setNewRevision
ContentEntityBase::setRevisionTranslationAffected public function Marks the current revision translation as affected. Overrides TranslatableRevisionableInterface::setRevisionTranslationAffected
ContentEntityBase::setRevisionTranslationAffectedEnforced public function Enforces the revision translation affected flag value. Overrides TranslatableRevisionableInterface::setRevisionTranslationAffectedEnforced
ContentEntityBase::setValidationRequired public function Sets whether entity validation is required before saving the entity. Overrides FieldableEntityInterface::setValidationRequired
ContentEntityBase::toArray public function Gets an array of all property values. Overrides EntityBase::toArray
ContentEntityBase::updateFieldLangcodes protected function Updates language for already instantiated fields.
ContentEntityBase::updateLoadedRevisionId public function Updates the loaded Revision ID with the revision ID. Overrides RevisionableInterface::updateLoadedRevisionId
ContentEntityBase::updateOriginalValues public function Updates the original values with the interim changes.
ContentEntityBase::uuid public function Gets the entity UUID (Universally Unique Identifier). Overrides EntityBase::uuid
ContentEntityBase::validate public function Validates the currently set values. Overrides FieldableEntityInterface::validate 1
ContentEntityBase::wasDefaultRevision public function Checks whether the entity object was a default revision when it was saved. Overrides RevisionableInterface::wasDefaultRevision
ContentEntityBase::__clone public function Magic method: Implements a deep clone.
ContentEntityBase::__construct public function Constructs an Entity object. Overrides EntityBase::__construct
ContentEntityBase::__get public function Implements the magic method for getting object properties.
ContentEntityBase::__isset public function Implements the magic method for isset().
ContentEntityBase::__set public function Implements the magic method for setting object properties.
ContentEntityBase::__sleep public function Overrides EntityBase::__sleep
ContentEntityBase::__unset public function Implements the magic method for unset().
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function Aliased as: traitSleep 2
DependencySerializationTrait::__wakeup public function 2
EntityBase::$enforceIsNew protected property Boolean indicating whether the entity should be forced to be new.
EntityBase::$entityTypeId protected property The entity type.
EntityBase::$typedData protected property A typed data object wrapping this entity.
EntityBase::create public static function Constructs a new entity object, without permanently saving it. Overrides EntityInterface::create
EntityBase::enforceIsNew public function Enforces an entity to be new. Overrides EntityInterface::enforceIsNew
EntityBase::entityTypeBundleInfo protected function Gets the entity type bundle info service.
EntityBase::entityTypeManager protected function Gets the entity type manager.
EntityBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyTrait::getCacheContexts
EntityBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyTrait::getCacheMaxAge
EntityBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyTrait::getCacheTags
EntityBase::getCacheTagsToInvalidate public function Returns the cache tags that should be used to invalidate caches. Overrides EntityInterface::getCacheTagsToInvalidate 4
EntityBase::getConfigDependencyKey public function Gets the key that is used to store configuration dependencies. Overrides EntityInterface::getConfigDependencyKey
EntityBase::getConfigDependencyName public function Gets the configuration dependency name. Overrides EntityInterface::getConfigDependencyName 1
EntityBase::getConfigTarget public function Gets the configuration target identifier for the entity. Overrides EntityInterface::getConfigTarget 1
EntityBase::getEntityType public function Gets the entity type definition. Overrides EntityInterface::getEntityType
EntityBase::getEntityTypeId public function Gets the ID of the type of the entity. Overrides EntityInterface::getEntityTypeId
EntityBase::getListCacheTagsToInvalidate protected function The list cache tags to invalidate for this entity.
EntityBase::getOriginalId public function Gets the original ID. Overrides EntityInterface::getOriginalId 1
EntityBase::getTypedData public function Gets a typed data object for this entity object. Overrides EntityInterface::getTypedData
EntityBase::hasLinkTemplate public function Indicates if a link template exists for a given key. Overrides EntityInterface::hasLinkTemplate
EntityBase::invalidateTagsOnDelete protected static function Invalidates an entity's cache tags upon delete. 1
EntityBase::invalidateTagsOnSave protected function Invalidates an entity's cache tags upon save. 1
EntityBase::isNew public function Determines whether the entity is new. Overrides EntityInterface::isNew 2
EntityBase::languageManager protected function Gets the language manager.
EntityBase::linkTemplates protected function Gets an array link templates. 1
EntityBase::load public static function Loads an entity. Overrides EntityInterface::load
EntityBase::loadMultiple public static function Loads one or more entities. Overrides EntityInterface::loadMultiple
EntityBase::postDelete public static function Acts on deleted entities before the delete hook is invoked. Overrides EntityInterface::postDelete 18
EntityBase::postLoad public static function Acts on loaded entities. Overrides EntityInterface::postLoad 2
EntityBase::preCreate public static function Changes the values of an entity before it is created. Overrides EntityInterface::preCreate 7
EntityBase::preDelete public static function Acts on entities before they are deleted and before hooks are invoked. Overrides EntityInterface::preDelete 6
EntityBase::setOriginalId public function Sets the original ID. Overrides EntityInterface::setOriginalId 1
EntityBase::toLink public function Generates the HTML for a link to this entity. Overrides EntityInterface::toLink
EntityBase::uriRelationships public function Gets a list of URI relationships supported by this entity. Overrides EntityInterface::uriRelationships
EntityBase::urlRouteParameters protected function Gets an array of placeholders for this entity. 2
EntityBase::uuidGenerator protected function Gets the UUID generator.
EntityChangedTrait::getChangedTime public function Gets the timestamp of the last entity change for the current translation.
EntityChangedTrait::getChangedTimeAcrossTranslations public function Returns the timestamp of the last entity change across all translations.
EntityChangedTrait::setChangedTime public function Sets the timestamp of the last entity change for the current translation.
EntityChangesDetectionTrait::getFieldsToSkipFromTranslationChangesCheck protected function Returns an array of field names to skip when checking for changes. Aliased as: traitGetFieldsToSkipFromTranslationChangesCheck
EntityOwnerTrait::getDefaultEntityOwner public static function Default value callback for 'owner' base field. 1
EntityOwnerTrait::getOwner public function 1
EntityOwnerTrait::getOwnerId public function
EntityOwnerTrait::ownerBaseFieldDefinitions public static function Returns an array of base field definitions for entity owners.
EntityOwnerTrait::setOwner public function
EntityOwnerTrait::setOwnerId public function
QuizResult::baseFieldDefinitions public static function Provides base field definitions for an entity type. Overrides ContentEntityBase::baseFieldDefinitions
QuizResult::canReview function Can the quiz taker view the requested review?
QuizResult::copyToQuizResult function Copy this result's answers onto another Quiz result, based on the new Quiz result's settings.
QuizResult::delete public function Delete all result answers when a result is deleted. Overrides EntityBase::delete
QuizResult::finalize function Score a quiz result.
QuizResult::findOldResult public function Find a result that is not the same as the passed result.
QuizResult::getAccount function
QuizResult::getLayout public function Get the layout for this quiz result.
QuizResult::getQuiz public function Get the Quiz of this result.
QuizResult::hasReview public function Can the quiz taker view any reviews right now?
QuizResult::isTimeReached function Determine if the time limit has been reached for this attempt.
QuizResult::label public function Get the label for this quiz result. Overrides ContentEntityBase::label
QuizResult::maintainResults function Mark results as invalid for a quiz according to the keep results setting.
QuizResult::save public function Save the Quiz result and do any post-processing to the result. Overrides EntityBase::save
QuizResult::score function Calculates the score user received on quiz.
QuizResult::setQuestion function Update the session for this quiz to the active question.
QuizResult::toUrl public function Quiz results are never viewed outside of a Quiz, so we enforce that a Quiz route parameter is added. Overrides EntityBase::toUrl
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SynchronizableEntityTrait::$isSyncing protected property Whether this entity is being created, updated or deleted through a synchronization process.
SynchronizableEntityTrait::isSyncing public function
SynchronizableEntityTrait::setSyncing public function
TranslationStatusInterface::TRANSLATION_CREATED constant Status code identifying a newly created translation.
TranslationStatusInterface::TRANSLATION_EXISTING constant Status code identifying an existing translation.
TranslationStatusInterface::TRANSLATION_REMOVED constant Status code identifying a removed translation.