You are here

public function CalculateValue::execute in Business Rules 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/BusinessRulesAction/CalculateValue.php \Drupal\business_rules\Plugin\BusinessRulesAction\CalculateValue::execute()

Execute the action.

Parameters

\Drupal\business_rules\ActionInterface $action: The configured action.

\Drupal\business_rules\Events\BusinessRulesEvent $event: The event that has triggered the action.

Return value

array The render array to be showed on debug block.

Overrides BusinessRulesActionPlugin::execute

File

src/Plugin/BusinessRulesAction/CalculateValue.php, line 138

Class

CalculateValue
Class CalculateValue.

Namespace

Drupal\business_rules\Plugin\BusinessRulesAction

Code

public function execute(ActionInterface $action, BusinessRulesEvent $event) {

  /** @var \Drupal\business_rules\VariablesSet $event_variables */
  $event_variables = $event
    ->getArgument('variables');
  $raw_formula = $action
    ->getSettings('formula');
  $formula = $this
    ->processVariables($raw_formula, $event_variables);
  $variable = $action
    ->getSettings('variable');

  // Check if formula is safe.
  $allowed_values = str_split('()+-*/% ');
  $allowed_values[] = chr(10);
  $allowed_values[] = '\\r';
  $allowed_values[] = '\\n';
  if (is_numeric(str_replace($allowed_values, '', $formula))) {
    try {
      $formula_result = eval('return ' . $formula . ';');
      $success = TRUE;
    } catch (\Exception $e) {
      $formula_result = NULL;
      $success = FALSE;
    }
  }
  else {
    $formula_result = $formula;
    $success = FALSE;
  }
  $event_variables
    ->replaceValue($variable, $formula_result);
  if ($success) {
    $result = [
      '#type' => 'markup',
      '#markup' => t('Formula "%raw_formula" transformed into "%formula" with the result: "%result" assigned to variable "%variable".', [
        '%raw_formula' => $raw_formula,
        '%formula' => $formula,
        '%result' => $formula_result,
      ]),
    ];
  }
  else {
    $result = [
      '#type' => 'markup',
      '#markup' => t('The expression: "%raw_formula" processed as "%formula" could not be evaluated. Please, make sure it is a valid numeric expression.', [
        '%raw_formula' => $raw_formula,
        '%formula' => $formula,
      ]),
    ];
  }
  return $result;
}