annotate core/lib/Drupal/Core/Utility/Token.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 4c8ae668cc8c
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Utility;
Chris@0 4
Chris@0 5 use Drupal\Component\Render\HtmlEscapedText;
Chris@0 6 use Drupal\Component\Render\MarkupInterface;
Chris@0 7 use Drupal\Core\Cache\CacheableDependencyInterface;
Chris@0 8 use Drupal\Core\Cache\CacheBackendInterface;
Chris@0 9 use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
Chris@0 10 use Drupal\Core\Extension\ModuleHandlerInterface;
Chris@0 11 use Drupal\Core\Language\LanguageInterface;
Chris@0 12 use Drupal\Core\Language\LanguageManagerInterface;
Chris@0 13 use Drupal\Core\Render\AttachmentsInterface;
Chris@0 14 use Drupal\Core\Render\BubbleableMetadata;
Chris@0 15 use Drupal\Core\Render\RendererInterface;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * Drupal placeholder/token replacement system.
Chris@0 19 *
Chris@0 20 * API functions for replacing placeholders in text with meaningful values.
Chris@0 21 *
Chris@0 22 * For example: When configuring automated emails, an administrator enters
Chris@0 23 * standard text for the email. Variables like the title of a node and the date
Chris@0 24 * the email was sent can be entered as placeholders like [node:title] and
Chris@0 25 * [date:short]. When a Drupal module prepares to send the email, it can call
Chris@0 26 * the Token::replace() function, passing in the text. The token system will
Chris@0 27 * scan the text for placeholder tokens, give other modules an opportunity to
Chris@0 28 * replace them with meaningful text, then return the final product to the
Chris@0 29 * original module.
Chris@0 30 *
Chris@0 31 * Tokens follow the form: [$type:$name], where $type is a general class of
Chris@0 32 * tokens like 'node', 'user', or 'comment' and $name is the name of a given
Chris@0 33 * placeholder. For example, [node:title] or [node:created:since].
Chris@0 34 *
Chris@0 35 * In addition to raw text containing placeholders, modules may pass in an array
Chris@0 36 * of objects to be used when performing the replacement. The objects should be
Chris@0 37 * keyed by the token type they correspond to. For example:
Chris@0 38 *
Chris@0 39 * @code
Chris@0 40 * // Load a node and a user, then replace tokens in the text.
Chris@0 41 * $text = 'On [date:short], [user:name] read [node:title].';
Chris@0 42 * $node = Node::load(1);
Chris@0 43 * $user = User::load(1);
Chris@0 44 *
Chris@0 45 * // [date:...] tokens use the current date automatically.
Chris@0 46 * $data = array('node' => $node, 'user' => $user);
Chris@0 47 * return Token::replace($text, $data);
Chris@0 48 * @endcode
Chris@0 49 *
Chris@0 50 * Some tokens may be chained in the form of [$type:$pointer:$name], where $type
Chris@0 51 * is a normal token type, $pointer is a reference to another token type, and
Chris@0 52 * $name is the name of a given placeholder. For example, [node:author:mail]. In
Chris@0 53 * that example, 'author' is a pointer to the 'user' account that created the
Chris@0 54 * node, and 'mail' is a placeholder available for any 'user'.
Chris@0 55 *
Chris@0 56 * @see Token::replace()
Chris@0 57 * @see hook_tokens()
Chris@0 58 * @see hook_token_info()
Chris@0 59 */
Chris@0 60 class Token {
Chris@0 61
Chris@0 62 /**
Chris@0 63 * The tag to cache token info with.
Chris@0 64 */
Chris@0 65 const TOKEN_INFO_CACHE_TAG = 'token_info';
Chris@0 66
Chris@0 67 /**
Chris@0 68 * The token cache.
Chris@0 69 *
Chris@0 70 * @var \Drupal\Core\Cache\CacheBackendInterface
Chris@0 71 */
Chris@0 72 protected $cache;
Chris@0 73
Chris@0 74 /**
Chris@0 75 * The language manager.
Chris@0 76 *
Chris@0 77 * @var \Drupal\Core\Language\LanguageManagerInterface
Chris@0 78 */
Chris@0 79 protected $languageManager;
Chris@0 80
Chris@0 81 /**
Chris@0 82 * Token definitions.
Chris@0 83 *
Chris@0 84 * @var array[]|null
Chris@0 85 * An array of token definitions, or NULL when the definitions are not set.
Chris@0 86 *
Chris@0 87 * @see self::setInfo()
Chris@0 88 * @see self::getInfo()
Chris@0 89 * @see self::resetInfo()
Chris@0 90 */
Chris@0 91 protected $tokenInfo;
Chris@0 92
Chris@0 93 /**
Chris@0 94 * The module handler service.
Chris@0 95 *
Chris@0 96 * @var \Drupal\Core\Extension\ModuleHandlerInterface
Chris@0 97 */
Chris@0 98 protected $moduleHandler;
Chris@0 99
Chris@0 100 /**
Chris@0 101 * The cache tags invalidator.
Chris@0 102 *
Chris@0 103 * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
Chris@0 104 */
Chris@0 105 protected $cacheTagsInvalidator;
Chris@0 106
Chris@0 107 /**
Chris@0 108 * The renderer.
Chris@0 109 *
Chris@0 110 * @var \Drupal\Core\Render\RendererInterface
Chris@0 111 */
Chris@0 112 protected $renderer;
Chris@0 113
Chris@0 114 /**
Chris@0 115 * Constructs a new class instance.
Chris@0 116 *
Chris@0 117 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
Chris@0 118 * The module handler.
Chris@0 119 * @param \Drupal\Core\Cache\CacheBackendInterface $cache
Chris@0 120 * The token cache.
Chris@0 121 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
Chris@0 122 * The language manager.
Chris@0 123 * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
Chris@0 124 * The cache tags invalidator.
Chris@0 125 * @param \Drupal\Core\Render\RendererInterface $renderer
Chris@0 126 * The renderer.
Chris@0 127 */
Chris@0 128 public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer) {
Chris@0 129 $this->cache = $cache;
Chris@0 130 $this->languageManager = $language_manager;
Chris@0 131 $this->moduleHandler = $module_handler;
Chris@0 132 $this->cacheTagsInvalidator = $cache_tags_invalidator;
Chris@0 133 $this->renderer = $renderer;
Chris@0 134 }
Chris@0 135
Chris@0 136 /**
Chris@0 137 * Replaces all tokens in a given string with appropriate values.
Chris@0 138 *
Chris@0 139 * @param string $text
Chris@0 140 * An HTML string containing replaceable tokens. The caller is responsible
Chris@0 141 * for calling \Drupal\Component\Utility\Html::escape() in case the $text
Chris@0 142 * was plain text.
Chris@0 143 * @param array $data
Chris@0 144 * (optional) An array of keyed objects. For simple replacement scenarios
Chris@0 145 * 'node', 'user', and others are common keys, with an accompanying node or
Chris@0 146 * user object being the value. Some token types, like 'site', do not require
Chris@0 147 * any explicit information from $data and can be replaced even if it is
Chris@0 148 * empty.
Chris@0 149 * @param array $options
Chris@0 150 * (optional) A keyed array of settings and flags to control the token
Chris@0 151 * replacement process. Supported options are:
Chris@0 152 * - langcode: A language code to be used when generating locale-sensitive
Chris@0 153 * tokens.
Chris@0 154 * - callback: A callback function that will be used to post-process the
Chris@0 155 * array of token replacements after they are generated.
Chris@0 156 * - clear: A boolean flag indicating that tokens should be removed from the
Chris@0 157 * final text if no replacement value can be generated.
Chris@0 158 * @param \Drupal\Core\Render\BubbleableMetadata|null $bubbleable_metadata
Chris@0 159 * (optional) An object to which static::generate() and the hooks and
Chris@0 160 * functions that it invokes will add their required bubbleable metadata.
Chris@0 161 *
Chris@0 162 * To ensure that the metadata associated with the token replacements gets
Chris@0 163 * attached to the same render array that contains the token-replaced text,
Chris@0 164 * callers of this method are encouraged to pass in a BubbleableMetadata
Chris@0 165 * object and apply it to the corresponding render array. For example:
Chris@0 166 * @code
Chris@0 167 * $bubbleable_metadata = new BubbleableMetadata();
Chris@0 168 * $build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
Chris@0 169 * $bubbleable_metadata->applyTo($build);
Chris@0 170 * @endcode
Chris@0 171 *
Chris@0 172 * When the caller does not pass in a BubbleableMetadata object, this
Chris@0 173 * method creates a local one, and applies the collected metadata to the
Chris@0 174 * Renderer's currently active render context.
Chris@0 175 *
Chris@0 176 * @return string
Chris@0 177 * The token result is the entered HTML text with tokens replaced. The
Chris@0 178 * caller is responsible for choosing the right escaping / sanitization. If
Chris@0 179 * the result is intended to be used as plain text, using
Chris@0 180 * PlainTextOutput::renderFromHtml() is recommended. If the result is just
Chris@0 181 * printed as part of a template relying on Twig autoescaping is possible,
Chris@0 182 * otherwise for example the result can be put into #markup, in which case
Chris@0 183 * it would be sanitized by Xss::filterAdmin().
Chris@0 184 */
Chris@0 185 public function replace($text, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
Chris@0 186 $text_tokens = $this->scan($text);
Chris@0 187 if (empty($text_tokens)) {
Chris@0 188 return $text;
Chris@0 189 }
Chris@0 190
Chris@0 191 $bubbleable_metadata_is_passed_in = (bool) $bubbleable_metadata;
Chris@0 192 $bubbleable_metadata = $bubbleable_metadata ?: new BubbleableMetadata();
Chris@0 193
Chris@0 194 $replacements = [];
Chris@0 195 foreach ($text_tokens as $type => $tokens) {
Chris@0 196 $replacements += $this->generate($type, $tokens, $data, $options, $bubbleable_metadata);
Chris@0 197 if (!empty($options['clear'])) {
Chris@0 198 $replacements += array_fill_keys($tokens, '');
Chris@0 199 }
Chris@0 200 }
Chris@0 201
Chris@0 202 // Escape the tokens, unless they are explicitly markup.
Chris@0 203 foreach ($replacements as $token => $value) {
Chris@0 204 $replacements[$token] = $value instanceof MarkupInterface ? $value : new HtmlEscapedText($value);
Chris@0 205 }
Chris@0 206
Chris@0 207 // Optionally alter the list of replacement values.
Chris@0 208 if (!empty($options['callback'])) {
Chris@0 209 $function = $options['callback'];
Chris@0 210 $function($replacements, $data, $options, $bubbleable_metadata);
Chris@0 211 }
Chris@0 212
Chris@0 213 $tokens = array_keys($replacements);
Chris@0 214 $values = array_values($replacements);
Chris@0 215
Chris@0 216 // If a local $bubbleable_metadata object was created, apply the metadata
Chris@0 217 // it collected to the renderer's currently active render context.
Chris@0 218 if (!$bubbleable_metadata_is_passed_in && $this->renderer->hasRenderContext()) {
Chris@0 219 $build = [];
Chris@0 220 $bubbleable_metadata->applyTo($build);
Chris@0 221 $this->renderer->render($build);
Chris@0 222 }
Chris@0 223
Chris@0 224 return str_replace($tokens, $values, $text);
Chris@0 225 }
Chris@0 226
Chris@0 227 /**
Chris@0 228 * Builds a list of all token-like patterns that appear in the text.
Chris@0 229 *
Chris@0 230 * @param string $text
Chris@0 231 * The text to be scanned for possible tokens.
Chris@0 232 *
Chris@0 233 * @return array
Chris@0 234 * An associative array of discovered tokens, grouped by type.
Chris@0 235 */
Chris@0 236 public function scan($text) {
Chris@0 237 // Matches tokens with the following pattern: [$type:$name]
Chris@0 238 // $type and $name may not contain [ ] characters.
Chris@0 239 // $type may not contain : or whitespace characters, but $name may.
Chris@0 240 preg_match_all('/
Chris@0 241 \[ # [ - pattern start
Chris@0 242 ([^\s\[\]:]+) # match $type not containing whitespace : [ or ]
Chris@0 243 : # : - separator
Chris@0 244 ([^\[\]]+) # match $name not containing [ or ]
Chris@0 245 \] # ] - pattern end
Chris@0 246 /x', $text, $matches);
Chris@0 247
Chris@0 248 $types = $matches[1];
Chris@0 249 $tokens = $matches[2];
Chris@0 250
Chris@0 251 // Iterate through the matches, building an associative array containing
Chris@0 252 // $tokens grouped by $types, pointing to the version of the token found in
Chris@0 253 // the source text. For example, $results['node']['title'] = '[node:title]';
Chris@0 254 $results = [];
Chris@0 255 for ($i = 0; $i < count($tokens); $i++) {
Chris@0 256 $results[$types[$i]][$tokens[$i]] = $matches[0][$i];
Chris@0 257 }
Chris@0 258
Chris@0 259 return $results;
Chris@0 260 }
Chris@0 261
Chris@0 262 /**
Chris@0 263 * Generates replacement values for a list of tokens.
Chris@0 264 *
Chris@0 265 * @param string $type
Chris@0 266 * The type of token being replaced. 'node', 'user', and 'date' are common.
Chris@0 267 * @param array $tokens
Chris@0 268 * An array of tokens to be replaced, keyed by the literal text of the token
Chris@0 269 * as it appeared in the source text.
Chris@0 270 * @param array $data
Chris@0 271 * An array of keyed objects. For simple replacement scenarios: 'node',
Chris@0 272 * 'user', and others are common keys, with an accompanying node or user
Chris@0 273 * object being the value. Some token types, like 'site', do not require
Chris@0 274 * any explicit information from $data and can be replaced even if it is
Chris@0 275 * empty.
Chris@0 276 * @param array $options
Chris@0 277 * A keyed array of settings and flags to control the token replacement
Chris@0 278 * process. Supported options are:
Chris@0 279 * - langcode: A language code to be used when generating locale-sensitive
Chris@0 280 * tokens.
Chris@0 281 * - callback: A callback function that will be used to post-process the
Chris@0 282 * array of token replacements after they are generated. Can be used when
Chris@0 283 * modules require special formatting of token text, for example URL
Chris@0 284 * encoding or truncation to a specific length.
Chris@0 285 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
Chris@0 286 * The bubbleable metadata. This is passed to the token replacement
Chris@0 287 * implementations so that they can attach their metadata.
Chris@0 288 *
Chris@0 289 * @return array
Chris@0 290 * An associative array of replacement values, keyed by the original 'raw'
Chris@0 291 * tokens that were found in the source text. For example:
Chris@0 292 * $results['[node:title]'] = 'My new node';
Chris@0 293 *
Chris@0 294 * @see hook_tokens()
Chris@0 295 * @see hook_tokens_alter()
Chris@0 296 */
Chris@0 297 public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
Chris@0 298 foreach ($data as $object) {
Chris@0 299 if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) {
Chris@0 300 $bubbleable_metadata->addCacheableDependency($object);
Chris@0 301 }
Chris@0 302 }
Chris@0 303
Chris@0 304 $replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]);
Chris@0 305
Chris@0 306 // Allow other modules to alter the replacements.
Chris@0 307 $context = [
Chris@0 308 'type' => $type,
Chris@0 309 'tokens' => $tokens,
Chris@0 310 'data' => $data,
Chris@0 311 'options' => $options,
Chris@0 312 ];
Chris@0 313 $this->moduleHandler->alter('tokens', $replacements, $context, $bubbleable_metadata);
Chris@0 314
Chris@0 315 return $replacements;
Chris@0 316 }
Chris@0 317
Chris@0 318 /**
Chris@0 319 * Returns a list of tokens that begin with a specific prefix.
Chris@0 320 *
Chris@0 321 * Used to extract a group of 'chained' tokens (such as [node:author:name])
Chris@0 322 * from the full list of tokens found in text. For example:
Chris@0 323 * @code
Chris@0 324 * $data = array(
Chris@0 325 * 'author:name' => '[node:author:name]',
Chris@0 326 * 'title' => '[node:title]',
Chris@0 327 * 'created' => '[node:created]',
Chris@0 328 * );
Chris@0 329 * $results = Token::findWithPrefix($data, 'author');
Chris@0 330 * $results == array('name' => '[node:author:name]');
Chris@0 331 * @endcode
Chris@0 332 *
Chris@0 333 * @param array $tokens
Chris@0 334 * A keyed array of tokens, and their original raw form in the source text.
Chris@0 335 * @param string $prefix
Chris@0 336 * A textual string to be matched at the beginning of the token.
Chris@0 337 * @param string $delimiter
Chris@0 338 * (optional) A string containing the character that separates the prefix from
Chris@0 339 * the rest of the token. Defaults to ':'.
Chris@0 340 *
Chris@0 341 * @return array
Chris@0 342 * An associative array of discovered tokens, with the prefix and delimiter
Chris@0 343 * stripped from the key.
Chris@0 344 */
Chris@0 345 public function findWithPrefix(array $tokens, $prefix, $delimiter = ':') {
Chris@0 346 $results = [];
Chris@0 347 foreach ($tokens as $token => $raw) {
Chris@0 348 $parts = explode($delimiter, $token, 2);
Chris@0 349 if (count($parts) == 2 && $parts[0] == $prefix) {
Chris@0 350 $results[$parts[1]] = $raw;
Chris@0 351 }
Chris@0 352 }
Chris@0 353 return $results;
Chris@0 354 }
Chris@0 355
Chris@0 356 /**
Chris@0 357 * Returns metadata describing supported tokens.
Chris@0 358 *
Chris@0 359 * The metadata array contains token type, name, and description data as well
Chris@0 360 * as an optional pointer indicating that the token chains to another set of
Chris@0 361 * tokens.
Chris@0 362 *
Chris@0 363 * @return array
Chris@0 364 * An associative array of token information, grouped by token type. The
Chris@0 365 * array structure is identical to that of hook_token_info().
Chris@0 366 *
Chris@0 367 * @see hook_token_info()
Chris@0 368 */
Chris@0 369 public function getInfo() {
Chris@0 370 if (is_null($this->tokenInfo)) {
Chris@0 371 $cache_id = 'token_info:' . $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
Chris@0 372 $cache = $this->cache->get($cache_id);
Chris@0 373 if ($cache) {
Chris@0 374 $this->tokenInfo = $cache->data;
Chris@0 375 }
Chris@0 376 else {
Chris@0 377 $this->tokenInfo = $this->moduleHandler->invokeAll('token_info');
Chris@0 378 $this->moduleHandler->alter('token_info', $this->tokenInfo);
Chris@0 379 $this->cache->set($cache_id, $this->tokenInfo, CacheBackendInterface::CACHE_PERMANENT, [
Chris@0 380 static::TOKEN_INFO_CACHE_TAG,
Chris@0 381 ]);
Chris@0 382 }
Chris@0 383 }
Chris@0 384
Chris@0 385 return $this->tokenInfo;
Chris@0 386 }
Chris@0 387
Chris@0 388 /**
Chris@0 389 * Sets metadata describing supported tokens.
Chris@0 390 *
Chris@0 391 * @param array $tokens
Chris@0 392 * Token metadata that has an identical structure to the return value of
Chris@0 393 * hook_token_info().
Chris@0 394 *
Chris@0 395 * @see hook_token_info()
Chris@0 396 */
Chris@0 397 public function setInfo(array $tokens) {
Chris@0 398 $this->tokenInfo = $tokens;
Chris@0 399 }
Chris@0 400
Chris@0 401 /**
Chris@0 402 * Resets metadata describing supported tokens.
Chris@0 403 */
Chris@0 404 public function resetInfo() {
Chris@0 405 $this->tokenInfo = NULL;
Chris@0 406 $this->cacheTagsInvalidator->invalidateTags([static::TOKEN_INFO_CACHE_TAG]);
Chris@0 407 }
Chris@0 408
Chris@0 409 }