Skip to content

Commit

Permalink
Issue backdrop#4672: Add tokens for random number and random hash.
Browse files Browse the repository at this point in the history
  • Loading branch information
indigoxela committed Dec 7, 2023
1 parent 84ab22b commit ea6729a
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions core/modules/system/system.tokens.inc
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ function system_token_info() {
'description' => t('Tokens related to arrays of strings.'),
'needs-data' => 'array',
);
$types['random'] = array(
'name' => t('Random'),
'description' => ('Tokens related to random data.'),
);

// Site-wide global tokens.
$site['name'] = array(
Expand Down Expand Up @@ -256,6 +260,21 @@ function system_token_info() {
'type' => 'user',
);

// Random tokens.
$random['number'] = array(
'name' => t('Number'),
'description' => t('A random number from 0 to @max.', array(
'@max' => mt_getrandmax(),
)),
);
$random['hash'] = array(
'name' => t('Hash'),
'description' => t('A random hash. The possible hashing algorithms are: @hash-algos.', array(
'@hash-algos' => implode(', ', hash_algos()),
)),
'dynamic' => TRUE,
);

return array(
'types' => $types,
'tokens' => array(
Expand All @@ -266,6 +285,7 @@ function system_token_info() {
'array' => $array,
'date' => $date,
'file' => $file,
'random' => $random,
),
);
}
Expand Down Expand Up @@ -601,6 +621,27 @@ function system_tokens($type, $tokens, array $data = array(), array $options = a
}
}

// Random tokens.
elseif ($type == 'random') {
foreach ($tokens as $name => $original) {
switch ($name) {
case 'number':
$replacements[$original] = mt_rand();
break;
}
}

// For [random:hash:?] dynamic token.
if ($hash_tokens = token_find_with_prefix($tokens, 'hash')) {
$algos = hash_algos();
foreach ($hash_tokens as $name => $original) {
if (in_array($name, $algos)) {
$replacements[$original] = hash($name, backdrop_random_bytes(55));
}
}
}
}

// If the token type specifics a 'needs-data' value, and the value is not
// present in $data, then throw an error.
if (!empty($GLOBALS['backdrop_test_info']['test_run_id'])) {
Expand Down

0 comments on commit ea6729a

Please sign in to comment.