You are here

public function TokenReplacer::replaceRandom in Menu Token 9.1.x

Same name and namespace in other branches
  1. 8 src/Service/TokenReplacer.php \Drupal\menu_token\Service\TokenReplacer::replaceRandom()

Replace token string with the value from context.

Parameters

string $token: Token to be replaced.

string $key: Key in token.

\Drupal\Core\Render\BubbleableMetadata $b: Bubable metadata for cache context.

Return value

array|string Returns replaced token.

File

src/Service/TokenReplacer.php, line 153

Class

TokenReplacer
TokenReplacer class.

Namespace

Drupal\menu_token\Service

Code

public function replaceRandom($token, $key, BubbleableMetadata $b) {
  $token_type = $this
    ->getTokenType($token);
  $entity_type = $this->tokenEntityMapper
    ->getEntityTypeForTokenType($token_type);
  $query = $this->entityTypeManager
    ->getStorage($entity_type)
    ->getQuery("AND");
  $user_ids = $query
    ->execute();

  // Pick one random user.
  $random_id = array_rand($user_ids, 1);
  $random_user = $this->entityTypeManager
    ->getStorage($entity_type)
    ->load($random_id);
  $replacement = $this->tokenService
    ->generate($token_type, [
    $key => $token,
  ], [
    $token_type => $random_user,
  ], [], $b);
  return $replacement;
}