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.

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);
}