You are here

class CalculateValue 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

Class CalculateValue.

@package Drupal\business_rules\Plugin\BusinessRulesAction

Plugin annotation


@BusinessRulesAction(
  id = "calculate_value",
  label = @Translation("Calculate a value"),
  group = @Translation("Variable"),
  description = @Translation("Calculate a numeric variable value. To composite a string value, use the 'Custom value' variable type."),
  isContextDependent = FALSE,
  hasTargetEntity = FALSE,
  hasTargetBundle = FALSE,
  hasTargetField = FALSE,
)

Hierarchy

Expanded class hierarchy of CalculateValue

File

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

Namespace

Drupal\business_rules\Plugin\BusinessRulesAction
View source
class CalculateValue extends BusinessRulesActionPlugin {

  /**
   * {@inheritdoc}
   */
  public function getSettingsForm(array &$form, FormStateInterface $form_state, ItemInterface $item) {
    $settings['variable'] = [
      '#type' => 'select',
      '#title' => t('Variable to store the result'),
      '#options' => $this->util
        ->getVariablesOptions([
        'custom_value_variable',
      ]),
      '#default_value' => $item
        ->getSettings('variable'),
      '#required' => TRUE,
      '#description' => t('The variable to store the value. Only variables type "Custom value" are allowed.'),
    ];
    $settings['formula'] = [
      '#type' => 'textarea',
      '#title' => t('Formula'),
      '#default_value' => $item
        ->getSettings('formula'),
      '#description' => $this
        ->getFormulaDescription(),
    ];
    return $settings;
  }

  /**
   * Get the formula description.
   *
   * @return array
   *   The render array.
   */
  private function getFormulaDescription() {
    $rows[] = [
      'example' => '{{variable_a}} + {{variable_b}}',
      'name' => t('Addition'),
      'result' => t('Sum of {{variable_a}} and {{variable_b}}'),
    ];
    $rows[] = [
      'example' => '{{variable_a}} - {{variable_b}}',
      'name' => t('Subtraction'),
      'result' => t('Difference of {{variable_a}} and {{variable_b}}'),
    ];
    $rows[] = [
      'example' => '{{variable_a}} * {{variable_b}}',
      'name' => t('Multiplication'),
      'result' => t('Product of {{variable_a}} and {{variable_b}}'),
    ];
    $rows[] = [
      'example' => '{{variable_a}} / {{variable_b}}',
      'name' => t('Division'),
      'result' => t('Quotient of {{variable_a}} and {{variable_b}}'),
    ];
    $rows[] = [
      'example' => '{{variable_a}} % {{variable_b}}',
      'name' => t('Modulo'),
      'result' => t('Remainder of {{variable_a}} divided by {{variable_b}}'),
    ];
    $rows[] = [
      'example' => '{{variable_a}} ** {{variable_b}}',
      'name' => t('Exponentiation'),
      'result' => t('Result of raising {{variable_a}} to the {{variable_b}}. PHP 5.6 and over.'),
    ];
    $rows[] = [
      'example' => '({{variable_a}} + {{variable_b}}) + {{variable_c}}',
      'name' => t('Parenthesis'),
      'result' => t('Change the precedence of the mathematical equation.'),
    ];
    $table = [
      '#type' => 'table',
      '#header' => [
        'example' => t('Example'),
        'name' => t('Name'),
        'result' => t('Result'),
      ],
      '#rows' => $rows,
    ];
    $output['help'] = [
      '#type' => 'details',
      '#title' => t('Formula helper'),
      '#collapsed' => TRUE,
    ];
    $output['help']['content'] = $table;
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function getVariables(ItemInterface $item) {
    $variableSet = parent::getVariables($item);
    $variableObj = new VariableObject($item
      ->getSettings('variable'), NULL, 'custom_value_variable');
    $variableSet
      ->append($variableObj);
    return $variableSet;
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BusinessRulesItemPluginBase::$processor protected property The business rules processor.
BusinessRulesItemPluginBase::$util protected property The business rules util.
BusinessRulesItemPluginBase::buildForm public function Form constructor. Overrides BusinessRulesItemPluginInterface::buildForm 11
BusinessRulesItemPluginBase::getDescription public function Provide a description of the item. Overrides BusinessRulesItemPluginInterface::getDescription
BusinessRulesItemPluginBase::getEditUrl public function Get the redirect url for the item edit-form route. Overrides BusinessRulesItemPluginInterface::getEditUrl
BusinessRulesItemPluginBase::getGroup public function Provide the group of the item. Overrides BusinessRulesItemPluginInterface::getGroup
BusinessRulesItemPluginBase::getRedirectUrl public function Get the redirect url for the item collection route. Overrides BusinessRulesItemPluginInterface::getRedirectUrl
BusinessRulesItemPluginBase::pregMatch public function Extract the variables from the plugin settings. Overrides BusinessRulesItemPluginInterface::pregMatch
BusinessRulesItemPluginBase::processSettings public function Process the item settings before it's saved. Overrides BusinessRulesItemPluginInterface::processSettings 19
BusinessRulesItemPluginBase::processTokenArraySetting private function Helper function to process tokens if the setting is an array.
BusinessRulesItemPluginBase::processTokens public function Process the tokens on the settings property for the item. Overrides BusinessRulesItemPluginInterface::processTokens
BusinessRulesItemPluginBase::processVariables public function Process the item replacing the variables by it's values. Overrides BusinessRulesItemPluginInterface::processVariables 1
BusinessRulesItemPluginBase::validateForm public function Plugin form validator. Overrides BusinessRulesItemPluginInterface::validateForm 11
BusinessRulesItemPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 11
BusinessRulesItemPluginInterface::VARIABLE_REGEX constant
CalculateValue::execute public function Execute the action. Overrides BusinessRulesActionPlugin::execute
CalculateValue::getFormulaDescription private function Get the formula description.
CalculateValue::getSettingsForm public function Return the form array. Overrides BusinessRulesItemPluginBase::getSettingsForm
CalculateValue::getVariables public function Return a variable set with all used variables on the item. Overrides BusinessRulesItemPluginBase::getVariables
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.