You are here

protected function Token::doReplace in Drupal 10

Replaces all tokens in a given string with appropriate values.

Parameters

bool $markup: TRUE to convert token values to markup, FALSE to convert to plain text.

string $text: A string containing replaceable tokens.

array $data: An array of keyed objects. See replace().

array $options: A keyed array of options. See replace().

\Drupal\Core\Render\BubbleableMetadata|null $bubbleable_metadata: (optional) Target for adding metadata. See replace().

Return value

string The token result is the entered string with tokens replaced.

File

core/lib/Drupal/Core/Utility/Token.php, line 228

Class

Token
Drupal placeholder/token replacement system.

Namespace

Drupal\Core\Utility

Code

protected function doReplace(bool $markup, string $text, array $data, array $options, BubbleableMetadata $bubbleable_metadata = NULL) : string {
  $text_tokens = $this
    ->scan($text);
  if (empty($text_tokens)) {
    return $text;
  }
  $bubbleable_metadata_is_passed_in = (bool) $bubbleable_metadata;
  $bubbleable_metadata = $bubbleable_metadata ?: new BubbleableMetadata();
  $replacements = [];
  foreach ($text_tokens as $type => $tokens) {
    $replacements += $this
      ->generate($type, $tokens, $data, $options, $bubbleable_metadata);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Each token value is markup if it implements MarkupInterface otherwise it
  // is plain text. Convert them, but only if needed. It can cause corruption
  // to render a string that's already plain text or to escape a string
  // that's already markup.
  foreach ($replacements as $token => $value) {
    if ($markup) {

      // Escape plain text tokens.
      $replacements[$token] = $value instanceof MarkupInterface ? $value : new HtmlEscapedText($value);
    }
    else {

      // Render markup tokens to plain text.
      $replacements[$token] = $value instanceof MarkupInterface ? PlainTextOutput::renderFromHtml($value) : $value;
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options, $bubbleable_metadata);
  }
  $tokens = array_keys($replacements);
  $values = array_values($replacements);

  // If a local $bubbleable_metadata object was created, apply the metadata
  // it collected to the renderer's currently active render context.
  if (!$bubbleable_metadata_is_passed_in && $this->renderer
    ->hasRenderContext()) {
    $build = [];
    $bubbleable_metadata
      ->applyTo($build);
    $this->renderer
      ->render($build);
  }
  return str_replace($tokens, $values, $text);
}