closedquestion-8.x-3.x-dev/src/Question/Textlabel/TriggerNumber.php
src/Question/Textlabel/TriggerNumber.php
<?php
namespace Drupal\closedquestion\Question\Textlabel;
use Drupal\closedquestion\Question\CqQuestionInterface;
/**
* Class TriggerNumber.
*
* @package Drupal\closedquestion\Question\Textlabel
*
* A trigger can set a TextLabel to a certain value depending on the input.
* It checks against a minimum and maximum value.
*/
class TriggerNumber {
/**
* The minimum value to check against. If NULL, there is no minimum.
*
* @var float
*/
public $min;
/**
* The maximum value to check against. If NULL, there is no maximum.
*
* @var float
*/
public $max;
/**
* The text to return when this Trigger matches.
*
* @var string
*/
public $text;
/**
* The question.
*
* Or other object that this item can query for things like the
* current answer, draggables and hotspots.
*
* @var \Drupal\closedquestion\Question\CqQuestionInterface
*/
public $context;
/**
* XML helper.
*
* @var \Drupal\closedquestion\Utility\XmlLib
*/
protected $xmlLib;
/**
* TriggerNumber constructor.
*/
public function __construct() {
$this->xmlLib = \Drupal::service('closedquestion.utility.xml_lib');
}
/**
* Initialise this Trigger by using values from the given XML node.
*
* @param \DOMElement $node
* DOMElement The node to use for initialisation.
* @param \Drupal\closedquestion\Question\CqQuestionInterface $context
* The question or other object that the mapping can query for
* things like the current answer, draggables, hotspots and the parsing of
* html.
*/
public function initFromNode(\DOMElement $node, CqQuestionInterface $context) {
$this->context = $context;
$this->text .= $this->xmlLib->getTextContent($node, $context, TRUE, TRUE);
$attribs = $node->attributes;
$itemMin = $attribs->getNamedItem('min');
if ($itemMin !== NULL) {
$this->min = (float) $itemMin->value;
}
$itemMax = $attribs->getNamedItem('max');
if ($itemMax !== NULL) {
$this->max = (float) $itemMax->value;
}
}
/**
* Check if the given input triggers this Trigger.
*
* @param mixed $input
* The input to check against. It it first cast to float.
*
* @return bool
* TRUE if this trigger matches, FALSE otherwise.
*/
public function matches($input) {
$input = (float) $input;
if (isset($this->min) && $input < $this->min) {
return FALSE;
}
if (isset($this->max) && $input > $this->max) {
return FALSE;
}
return TRUE;
}
/**
* Get the parsed text of this Trigger.
*
* @return string
* The text to show if this Trigger matches.
*/
public function getText() {
return $this->xmlLib->replaceTags($this->text, $this->context);
}
}
