3 namespace Drupal\Core\Utility;
5 use Drupal\Component\Render\HtmlEscapedText;
6 use Drupal\Component\Render\MarkupInterface;
7 use Drupal\Core\Cache\CacheableDependencyInterface;
8 use Drupal\Core\Cache\CacheBackendInterface;
9 use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
10 use Drupal\Core\Extension\ModuleHandlerInterface;
11 use Drupal\Core\Language\LanguageInterface;
12 use Drupal\Core\Language\LanguageManagerInterface;
13 use Drupal\Core\Render\AttachmentsInterface;
14 use Drupal\Core\Render\BubbleableMetadata;
15 use Drupal\Core\Render\RendererInterface;
18 * Drupal placeholder/token replacement system.
20 * API functions for replacing placeholders in text with meaningful values.
22 * For example: When configuring automated emails, an administrator enters
23 * standard text for the email. Variables like the title of a node and the date
24 * the email was sent can be entered as placeholders like [node:title] and
25 * [date:short]. When a Drupal module prepares to send the email, it can call
26 * the Token::replace() function, passing in the text. The token system will
27 * scan the text for placeholder tokens, give other modules an opportunity to
28 * replace them with meaningful text, then return the final product to the
31 * Tokens follow the form: [$type:$name], where $type is a general class of
32 * tokens like 'node', 'user', or 'comment' and $name is the name of a given
33 * placeholder. For example, [node:title] or [node:created:since].
35 * In addition to raw text containing placeholders, modules may pass in an array
36 * of objects to be used when performing the replacement. The objects should be
37 * keyed by the token type they correspond to. For example:
40 * // Load a node and a user, then replace tokens in the text.
41 * $text = 'On [date:short], [user:name] read [node:title].';
42 * $node = Node::load(1);
43 * $user = User::load(1);
45 * // [date:...] tokens use the current date automatically.
46 * $data = array('node' => $node, 'user' => $user);
47 * return Token::replace($text, $data);
50 * Some tokens may be chained in the form of [$type:$pointer:$name], where $type
51 * is a normal token type, $pointer is a reference to another token type, and
52 * $name is the name of a given placeholder. For example, [node:author:mail]. In
53 * that example, 'author' is a pointer to the 'user' account that created the
54 * node, and 'mail' is a placeholder available for any 'user'.
56 * @see Token::replace()
58 * @see hook_token_info()
63 * The tag to cache token info with.
65 const TOKEN_INFO_CACHE_TAG = 'token_info';
70 * @var \Drupal\Core\Cache\CacheBackendInterface
75 * The language manager.
77 * @var \Drupal\Core\Language\LanguageManagerInterface
79 protected $languageManager;
85 * An array of token definitions, or NULL when the definitions are not set.
87 * @see self::setInfo()
88 * @see self::getInfo()
89 * @see self::resetInfo()
94 * The module handler service.
96 * @var \Drupal\Core\Extension\ModuleHandlerInterface
98 protected $moduleHandler;
101 * The cache tags invalidator.
103 * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
105 protected $cacheTagsInvalidator;
110 * @var \Drupal\Core\Render\RendererInterface
115 * Constructs a new class instance.
117 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
118 * The module handler.
119 * @param \Drupal\Core\Cache\CacheBackendInterface $cache
121 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
122 * The language manager.
123 * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
124 * The cache tags invalidator.
125 * @param \Drupal\Core\Render\RendererInterface $renderer
128 public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer) {
129 $this->cache = $cache;
130 $this->languageManager = $language_manager;
131 $this->moduleHandler = $module_handler;
132 $this->cacheTagsInvalidator = $cache_tags_invalidator;
133 $this->renderer = $renderer;
137 * Replaces all tokens in a given string with appropriate values.
139 * @param string $text
140 * An HTML string containing replaceable tokens. The caller is responsible
141 * for calling \Drupal\Component\Utility\Html::escape() in case the $text
144 * (optional) An array of keyed objects. For simple replacement scenarios
145 * 'node', 'user', and others are common keys, with an accompanying node or
146 * user object being the value. Some token types, like 'site', do not require
147 * any explicit information from $data and can be replaced even if it is
149 * @param array $options
150 * (optional) A keyed array of settings and flags to control the token
151 * replacement process. Supported options are:
152 * - langcode: A language code to be used when generating locale-sensitive
154 * - callback: A callback function that will be used to post-process the
155 * array of token replacements after they are generated.
156 * - clear: A boolean flag indicating that tokens should be removed from the
157 * final text if no replacement value can be generated.
158 * @param \Drupal\Core\Render\BubbleableMetadata|null $bubbleable_metadata
159 * (optional) An object to which static::generate() and the hooks and
160 * functions that it invokes will add their required bubbleable metadata.
162 * To ensure that the metadata associated with the token replacements gets
163 * attached to the same render array that contains the token-replaced text,
164 * callers of this method are encouraged to pass in a BubbleableMetadata
165 * object and apply it to the corresponding render array. For example:
167 * $bubbleable_metadata = new BubbleableMetadata();
168 * $build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
169 * $bubbleable_metadata->applyTo($build);
172 * When the caller does not pass in a BubbleableMetadata object, this
173 * method creates a local one, and applies the collected metadata to the
174 * Renderer's currently active render context.
177 * The token result is the entered HTML text with tokens replaced. The
178 * caller is responsible for choosing the right escaping / sanitization. If
179 * the result is intended to be used as plain text, using
180 * PlainTextOutput::renderFromHtml() is recommended. If the result is just
181 * printed as part of a template relying on Twig autoescaping is possible,
182 * otherwise for example the result can be put into #markup, in which case
183 * it would be sanitized by Xss::filterAdmin().
185 public function replace($text, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
186 $text_tokens = $this->scan($text);
187 if (empty($text_tokens)) {
191 $bubbleable_metadata_is_passed_in = (bool) $bubbleable_metadata;
192 $bubbleable_metadata = $bubbleable_metadata ?: new BubbleableMetadata();
195 foreach ($text_tokens as $type => $tokens) {
196 $replacements += $this->generate($type, $tokens, $data, $options, $bubbleable_metadata);
197 if (!empty($options['clear'])) {
198 $replacements += array_fill_keys($tokens, '');
202 // Escape the tokens, unless they are explicitly markup.
203 foreach ($replacements as $token => $value) {
204 $replacements[$token] = $value instanceof MarkupInterface ? $value : new HtmlEscapedText($value);
207 // Optionally alter the list of replacement values.
208 if (!empty($options['callback'])) {
209 $function = $options['callback'];
210 $function($replacements, $data, $options, $bubbleable_metadata);
213 $tokens = array_keys($replacements);
214 $values = array_values($replacements);
216 // If a local $bubbleable_metadata object was created, apply the metadata
217 // it collected to the renderer's currently active render context.
218 if (!$bubbleable_metadata_is_passed_in && $this->renderer->hasRenderContext()) {
220 $bubbleable_metadata->applyTo($build);
221 $this->renderer->render($build);
224 return str_replace($tokens, $values, $text);
228 * Builds a list of all token-like patterns that appear in the text.
230 * @param string $text
231 * The text to be scanned for possible tokens.
234 * An associative array of discovered tokens, grouped by type.
236 public function scan($text) {
237 // Matches tokens with the following pattern: [$type:$name]
238 // $type and $name may not contain [ ] characters.
239 // $type may not contain : or whitespace characters, but $name may.
241 \[ # [ - pattern start
242 ([^\s\[\]:]+) # match $type not containing whitespace : [ or ]
244 ([^\[\]]+) # match $name not containing [ or ]
246 /x', $text, $matches);
248 $types = $matches[1];
249 $tokens = $matches[2];
251 // Iterate through the matches, building an associative array containing
252 // $tokens grouped by $types, pointing to the version of the token found in
253 // the source text. For example, $results['node']['title'] = '[node:title]';
255 for ($i = 0; $i < count($tokens); $i++) {
256 $results[$types[$i]][$tokens[$i]] = $matches[0][$i];
263 * Generates replacement values for a list of tokens.
265 * @param string $type
266 * The type of token being replaced. 'node', 'user', and 'date' are common.
267 * @param array $tokens
268 * An array of tokens to be replaced, keyed by the literal text of the token
269 * as it appeared in the source text.
271 * An array of keyed objects. For simple replacement scenarios: 'node',
272 * 'user', and others are common keys, with an accompanying node or user
273 * object being the value. Some token types, like 'site', do not require
274 * any explicit information from $data and can be replaced even if it is
276 * @param array $options
277 * A keyed array of settings and flags to control the token replacement
278 * process. Supported options are:
279 * - langcode: A language code to be used when generating locale-sensitive
281 * - callback: A callback function that will be used to post-process the
282 * array of token replacements after they are generated. Can be used when
283 * modules require special formatting of token text, for example URL
284 * encoding or truncation to a specific length.
285 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
286 * The bubbleable metadata. This is passed to the token replacement
287 * implementations so that they can attach their metadata.
290 * An associative array of replacement values, keyed by the original 'raw'
291 * tokens that were found in the source text. For example:
292 * $results['[node:title]'] = 'My new node';
295 * @see hook_tokens_alter()
297 public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
298 foreach ($data as $object) {
299 if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) {
300 $bubbleable_metadata->addCacheableDependency($object);
304 $replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]);
306 // Allow other modules to alter the replacements.
311 'options' => $options,
313 $this->moduleHandler->alter('tokens', $replacements, $context, $bubbleable_metadata);
315 return $replacements;
319 * Returns a list of tokens that begin with a specific prefix.
321 * Used to extract a group of 'chained' tokens (such as [node:author:name])
322 * from the full list of tokens found in text. For example:
325 * 'author:name' => '[node:author:name]',
326 * 'title' => '[node:title]',
327 * 'created' => '[node:created]',
329 * $results = Token::findWithPrefix($data, 'author');
330 * $results == array('name' => '[node:author:name]');
333 * @param array $tokens
334 * A keyed array of tokens, and their original raw form in the source text.
335 * @param string $prefix
336 * A textual string to be matched at the beginning of the token.
337 * @param string $delimiter
338 * (optional) A string containing the character that separates the prefix from
339 * the rest of the token. Defaults to ':'.
342 * An associative array of discovered tokens, with the prefix and delimiter
343 * stripped from the key.
345 public function findWithPrefix(array $tokens, $prefix, $delimiter = ':') {
347 foreach ($tokens as $token => $raw) {
348 $parts = explode($delimiter, $token, 2);
349 if (count($parts) == 2 && $parts[0] == $prefix) {
350 $results[$parts[1]] = $raw;
357 * Returns metadata describing supported tokens.
359 * The metadata array contains token type, name, and description data as well
360 * as an optional pointer indicating that the token chains to another set of
364 * An associative array of token information, grouped by token type. The
365 * array structure is identical to that of hook_token_info().
367 * @see hook_token_info()
369 public function getInfo() {
370 if (is_null($this->tokenInfo)) {
371 $cache_id = 'token_info:' . $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
372 $cache = $this->cache->get($cache_id);
374 $this->tokenInfo = $cache->data;
377 $this->tokenInfo = $this->moduleHandler->invokeAll('token_info');
378 $this->moduleHandler->alter('token_info', $this->tokenInfo);
379 $this->cache->set($cache_id, $this->tokenInfo, CacheBackendInterface::CACHE_PERMANENT, [
380 static::TOKEN_INFO_CACHE_TAG,
385 return $this->tokenInfo;
389 * Sets metadata describing supported tokens.
391 * @param array $tokens
392 * Token metadata that has an identical structure to the return value of
395 * @see hook_token_info()
397 public function setInfo(array $tokens) {
398 $this->tokenInfo = $tokens;
402 * Resets metadata describing supported tokens.
404 public function resetInfo() {
405 $this->tokenInfo = NULL;
406 $this->cacheTagsInvalidator->invalidateTags([static::TOKEN_INFO_CACHE_TAG]);