closedquestion-8.x-3.x-dev/src/Question/CqQuestionValue.php

src/Question/CqQuestionValue.php
<?php

/**
 * @file
 */

namespace Drupal\closedquestion\Question;

use Drupal\closedquestion\Entity\ClosedQuestionInterface;
use Drupal\closedquestion\Question\Mapping\CqFeedback;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class CqQuestionValue.
 *
 * Implementation of the Value question type.
 * The same functionality can be created with the Fillblanks question type.
 *
 * @package Drupal\closedquestion\Question
 */
class CqQuestionValue extends CqQuestionAbstract {

  /**
   * HTML containing the question-text.
   *
   * @var string
   */
  private $text;

  /**
   * The base-name used for form elements that need to be accessed by js.
   *
   * @var string
   */
  private $formElementName;

  /**
   * Ranges to check the student-given value against.
   *
   * @var \Drupal\closedquestion\Question\CqRange[]
   */
  private $ranges = array();

  /**
   * The unit the answer should be in.
   *
   * @var string
   */
  private $unit = '';

  /**
   * List of feedback items to use as general hints.
   *
   * @var \Drupal\closedquestion\Question\Mapping\CqFeedback[]
   */
  private $hints = array();

  /**
   * The feedback to give when the student gives the correct answer.
   *
   * @var \Drupal\closedquestion\Question\Mapping\CqFeedback
   */
  private $correctFeeback;

  /**
   * Constructs a value question object.
   *
   * @param CqUserAnswerInterface $userAnswer
   *   The CqUserAnswerInterface to use for storing the student's answer.
   * @param \Drupal\closedquestion\Entity\ClosedQuestionInterface $closedQuestion
   *   Closed question entity.
   */
  public function __construct(CqUserAnswerInterface $userAnswer, ClosedQuestionInterface $closedQuestion) {
    parent::__construct();
    $this->userAnswer = $userAnswer;
    $this->closedQuestion = $closedQuestion;
    $this->formElementName = 'xq_option_question' . $this->closedQuestion->id() . '_';
  }

  /**
   * Implements CqQuestionAbstract::getOutput()
   */
  public function getOutput() {
    $this->initialise();
    $retval = $this->formBuilder->getForm('\Drupal\closedquestion\Form\QuestionForm', $this->closedQuestion);
    $retval['#prefix'] = $this->prefix;
    $retval['#suffix'] = $this->postfix;
    return $retval;
  }

  /**
   * Implements CqQuestionAbstract::getFeedbackItems()
   */
  public function getFeedbackItems() {
    $tries = $this->userAnswer->getTries();
    $answer = $this->userAnswer->getAnswer();
    $feedback = array();
    if ($answer == NULL) {
      // If there is no answer, don't check any further.
      return $feedback;
    }
    if (!$this->isCorrect()) {
      foreach ($this->hints as $fb) {
        if ($fb->inRange($tries)) {
          $feedback[] = $fb;
        }
      }
    }

    foreach ($this->ranges as $rangeNr => $range) {
      if ($range->inRange($answer)) {
        $feedbacks = $range->getFeedback($tries);
        foreach ($feedbacks as $fb) {
          $feedback[] = $fb;
        }
      }
    }

    if ($this->isCorrect()) {
      if ($this->correctFeeback != NULL) {
        $feedback[] = $this->correctFeeback;
      }
    }
    $feedback = array_merge($feedback, $this->fireGetExtraFeedbackItems($this, $tries));
    return $feedback;
  }

  /**
   * Overrides CqQuestionAbstract::loadXml()
   */
  public function loadXml(\DOMNode $dom) {
    parent::loadXml($dom);


    foreach ($dom->childNodes as $node) {
      $name = mb_strtolower($node->nodeName);
      switch ($name) {
        case 'range':
          $this->ranges[] = new CqRange($node, $this);
          break;

        case 'unit':
          $this->unit = $this->xmlLib->getTextContent($node, $this);
          break;

        case 'text':
          $this->text = $this->xmlLib->getTextContent($node, $this);
          break;

        case 'hint':
          $this->hints[] = CqFeedback::newCqFeedback($node, $this);
          break;

        case 'correct':
          $this->correctFeeback = CqFeedback::newCqFeedback($node, $this);
          break;

        default:
          if (!in_array($name, $this->knownElements)) {
            $this->messenger->addMessage(t('Unknown node: @nodename', array('@nodename' => $node->nodeName)));
          }
          break;
      }
    }
  }

  /**
   * Implements CqQuestionAbstract::getForm()
   */
  public function getForm($formState) {
    $form = parent::getForm($formState);
    $answer = $this->userAnswer->getAnswer();

    $formPos = strpos($this->text, '<formblock/>');
    if ($formPos !== FALSE) {
      // Not using mb_substr since we use a strpos generated index.
      $preForm = substr($this->text, 0, $formPos);
      $postForm = substr($this->text, $formPos + 12);
    }
    else {
      $form['questionText'] = array(
        '#type' => 'item',
        '#markup' => $this->text,
      );
    }

    $form['answer'] = array(
      '#type' => 'textfield',
      '#field_suffix' => $this->unit,
      '#size' => 10,
      '#default_value' => $answer,
    );
    if ($formPos !== FALSE) {
      $form['answer']['#prefix'] = $preForm;
      $form['answer']['#suffix'] = $postForm;
    }

    // Insert standard feedback and submit elements.
    $wrapper_id = 'cq-feedback-wrapper_' . $this->formElementName;
    $this->insertFeedback($form, $wrapper_id);
    $this->insertSubmit($form, $wrapper_id);
    return $form;
  }

  /**
   * Implements CqQuestionAbstract::checkCorrect()
   */
  public function checkCorrect() {
    $answer = $this->userAnswer->getAnswer();
    foreach ($this->ranges as $rangeNr => $range) {
      if ($range->inRange($answer) && $range->getCorrect()) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * Implements CqQuestionAbstract::submitAnswer()
   */
  public function submitAnswer($form, FormStateInterface $form_state) {
    $this->userAnswer->setAnswer($form_state->getValue('answer'));
    $correct = $this->isCorrect(TRUE);
    if ($this->userAnswer->answerHasChanged()) {
      if (!$correct) {
        $this->userAnswer->increaseTries();
      }
      $this->userAnswer->store();
    }
  }

  /**
   * Implements CqQuestionAbstract::getAllText()
   */
  public function getAllText() {
    $this->initialise();
    $retval = array();
    $retval['text']['#markup'] = $this->text;

    if (count($this->hints) > 0) {
      $retval['hints'] = array(
        '#theme' => 'closedquestion_feedback_list',
        '#extended' => TRUE,
      );
      foreach ($this->hints as $fbitem) {
        $retval['hints']['items'][] = $fbitem->getAllText();
      }
    }

    if (count($this->ranges) > 0) {
      $retval['mappings'] = array(
        '#theme' => 'closedquestion_feedback_list',
        '#extended' => TRUE,
      );
      foreach ($this->ranges as $range) {
        $retval['mappings']['items'][] = $range->getAllText();
      }
    }

    $retval['#theme'] = 'closedquestion_question_general_text';
    return $retval;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc