function RulesTokenEvaluator::evaluate

Evaluate tokens.

We replace the tokens on our own as we cannot use token_replace(), because token usually assumes that $data['node'] is a of type node, which doesn't hold in general in our case. So we properly map variable names to variable data types and then run the replacement ourself.

Parameters

string $text: The text to evaluate.

array $options: A keyed array of settings and flags to control the processing. Supported options are:

  • language: A language object to be used when processing.
  • callback: A callback function that will be used to post-process replacements that might be incorporated, so they can be cleaned in a certain way.
  • sanitize: A boolean flag indicating whether incorporated replacements should be sanitized.

RulesState $state: The rules evaluation state.

Return value

The evaluated text.

Overrides RulesDataInputEvaluator::evaluate

File

modules/system.eval.inc, line 201

Class

RulesTokenEvaluator
A class implementing a rules input evaluator processing tokens.

Code

public function evaluate($text, $options, RulesState $state) {
  $var_info = $state->varInfo();
  $options += array(
    'sanitize' => FALSE,
  );
  $replacements = array();
  $data = array();
  // We also support replacing tokens in a list of textual values.
  $whole_text = is_array($text) ? implode('', $text) : $text;
  foreach (token_scan($whole_text) as $var_name => $tokens) {
    $var_name = str_replace('-', '_', $var_name);
    if (isset($var_info[$var_name]) && $token_type = _rules_system_token_map_type($var_info[$var_name]['type'])) {
      // We have to key $data with the type token uses for the variable.
      $data = rules_unwrap_data(array(
        $token_type => $state->get($var_name),
      ), array(
        $token_type => $var_info[$var_name],
      ));
      $replacements += token_generate($token_type, $tokens, $data, $options);
    }
    else {
      $replacements += token_generate($var_name, $tokens, array(), $options);
    }
    // Remove tokens if no replacement value is found. As token_replace() does
    // if 'clear' is set.
    $replacements += array_fill_keys($tokens, '');
  }
  // Optionally clean the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }
  // Actually apply the replacements.
  $tokens = array_keys($replacements);
  $values = array_values($replacements);
  if (is_array($text)) {
    foreach ($text as $i => $text_item) {
      $text[$i] = str_replace($tokens, $values, $text_item);
    }
    return $text;
  }
  return str_replace($tokens, $values, $text);
}