You are here

public function SimpleMathField::getValue in Views Simple Math Field 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/views/field/SimpleMathField.php \Drupal\views_simple_math_field\Plugin\views\field\SimpleMathField::getValue()

Throws

\Exception

Overrides FieldPluginBase::getValue

File

src/Plugin/views/field/SimpleMathField.php, line 415
Defines Drupal\views_simple_math_field\Plugin\views\field\SimpleMathField.

Class

SimpleMathField
Field handler to complete mathematical operation.

Namespace

Drupal\views_simple_math_field\Plugin\views\field

Code

public function getValue(ResultRow $values, $field = NULL) {
  parent::getValue($values, $field);
  $entity = $this
    ->getEntity($values);

  // Collect all the fields checked.
  $fields_in_formula = [];
  foreach ($this->options['fieldset_one']['data_field'] as $key => $value) {
    if ($value) {
      $raw_field_in_formula = $this
        ->getFieldValue($values, $entity, $key);

      // Filter and sanitize out the float values.
      if (preg_match('/^.*?([\\d]+(?:\\.[\\d]+)?).*?$/', $raw_field_in_formula, $match)) {
        $raw_field_in_formula_sane = floatval($match[0]);
        $fields_in_formula['@' . $key] = filter_var($raw_field_in_formula_sane, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
      }
      else {
        $fields_in_formula['@' . $key] = 0;
      }
    }
  }

  // Format the numbers to a string that EvalMath can evaluate.
  $formula = new FormattableMarkup($this->options['fieldset_one']['formula'], $fields_in_formula);
  $m = new EvalMath();
  try {
    $result = $m
      ->evaluate($formula);
  } catch (DivisionByZeroException $e) {
    \Drupal::logger('views_simple_math_field')
      ->error('DivisionByZeroException');
  }

  // Return the value if evaluate is successful.
  return $result ?? NULL;
}