Pass User object to Token::replace I've the following code (sample) that runs on Cron and sends SMS to users.
$token = \Drupal::token();
$message = Hey, [current-user:account-name];
$message_value = $token-&gt;replace($message);
  

When cron run, Getting the SMS text as 'Hey Anonymous' This works correctly on site when user logins in. but not on cron.
So I tried to pass the user object to replace the token like follows but that doesn't work. Getting same result.
use Drupal\user\Entity\User;
$user = User::load($uid);
$message_value = $token-&gt;replace($message,['user' =&gt; $user]);

There are so many nodes created using this token. So I can't edit them all with new/custom token. So Is there any way to replace the user token, without writing a custom token?
The other workaround is to use str_replace like follows, but there might exists other user tokens in the same text. so not preferable.
  $message_value = str_replace('[current-user:account-name]', $name, $message);

Any suggestions?
The current-user token will always take its data from the current user, you can't override it with parameters. See user_tokens:
if ($type == 'current-user') {
  $account = User::load(\Drupal::currentUser()
    -&gt;id());
  $bubbleable_metadata
    -&gt;addCacheContexts([
    'user',
  ]);
  $replacements += $token_service
    -&gt;generate('user', $tokens, array(
    'user' =&gt; $account,
  ), $options, $bubbleable_metadata);
}

If you need to control the account object used for the token, use user instead
$message = 'Hey, [user:account-name]';
$message_value = $token-&gt;replace($message, ['user' =&gt; $account]);