Currently token_replace() still continues to execute even if it doesn't find any tokens to generate/replace in the text.
We should add a return if token_replace() is empty.
Before:
function token_replace($text, array $data = array(), array $options = array()) {
$replacements = array();
foreach (token_scan($text) as $type => $tokens) {
$replacements += token_generate($type, $tokens, $data, $options);
if (!empty($options['clear'])) {
$replacements += array_fill_keys($tokens, '');
}
}
// Optionally alter the list of replacement values.
if (!empty($options['callback']) && function_exists($options['callback'])) {
$function = $options['callback'];
$function($replacements, $data, $options);
}
$tokens = array_keys($replacements);
$values = array_values($replacements);
return str_replace($tokens, $values, $text);
}
After:
function token_replace($text, array $data = array(), array $options = array()) {
$scanned_tokens = token_scan($text);
if (empty($scanned_tokens)) {
return $text;
}
$replacements = array();
foreach ($scanned_tokens as $type => $tokens) {
$replacements += token_generate($type, $tokens, $data, $options);
if (!empty($options['clear'])) {
$replacements += array_fill_keys($tokens, '');
}
}
// Optionally alter the list of replacement values.
if (!empty($options['callback']) && function_exists($options['callback'])) {
$function = $options['callback'];
$function($replacements, $data, $options);
}
$tokens = array_keys($replacements);
$values = array_values($replacements);
return str_replace($tokens, $values, $text);
}
Comments
Comment #1
dave reidComment #2
dave reidComment #3
dave reidComment #4
dave reidWith a test.
Comment #6
dave reidTry that again.
Comment #7
sunExcellent!
Comment #8
sun#6: 1346166-token-replace-performance-no-tokens.patch queued for re-testing.
Comment #9
tstoecklerToo scared to un-RTBC a patch by Dave Reid reviewed by sun :), but I think this would be a very valid place for a comment. If you look at the "before" function in the op without the context of this issue, then you think nothing is wrong (at least I did...).
Comment #10
dries commentedCommitted to 8.x and back-ported to 7.x.
Comment #12
cweagansUpdating tags per http://drupal.org/node/1517250