Chris@0: $node, 'user' => $user); Chris@0: * return Token::replace($text, $data); Chris@0: * @endcode Chris@0: * Chris@0: * Some tokens may be chained in the form of [$type:$pointer:$name], where $type Chris@0: * is a normal token type, $pointer is a reference to another token type, and Chris@0: * $name is the name of a given placeholder. For example, [node:author:mail]. In Chris@0: * that example, 'author' is a pointer to the 'user' account that created the Chris@0: * node, and 'mail' is a placeholder available for any 'user'. Chris@0: * Chris@0: * @see Token::replace() Chris@0: * @see hook_tokens() Chris@0: * @see hook_token_info() Chris@0: */ Chris@0: class Token { Chris@0: Chris@0: /** Chris@0: * The tag to cache token info with. Chris@0: */ Chris@0: const TOKEN_INFO_CACHE_TAG = 'token_info'; Chris@0: Chris@0: /** Chris@0: * The token cache. Chris@0: * Chris@0: * @var \Drupal\Core\Cache\CacheBackendInterface Chris@0: */ Chris@0: protected $cache; Chris@0: Chris@0: /** Chris@0: * The language manager. Chris@0: * Chris@0: * @var \Drupal\Core\Language\LanguageManagerInterface Chris@0: */ Chris@0: protected $languageManager; Chris@0: Chris@0: /** Chris@0: * Token definitions. Chris@0: * Chris@0: * @var array[]|null Chris@0: * An array of token definitions, or NULL when the definitions are not set. Chris@0: * Chris@0: * @see self::setInfo() Chris@0: * @see self::getInfo() Chris@0: * @see self::resetInfo() Chris@0: */ Chris@0: protected $tokenInfo; Chris@0: Chris@0: /** Chris@0: * The module handler service. Chris@0: * Chris@0: * @var \Drupal\Core\Extension\ModuleHandlerInterface Chris@0: */ Chris@0: protected $moduleHandler; Chris@0: Chris@0: /** Chris@0: * The cache tags invalidator. Chris@0: * Chris@0: * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface Chris@0: */ Chris@0: protected $cacheTagsInvalidator; Chris@0: Chris@0: /** Chris@0: * The renderer. Chris@0: * Chris@0: * @var \Drupal\Core\Render\RendererInterface Chris@0: */ Chris@0: protected $renderer; Chris@0: Chris@0: /** Chris@0: * Constructs a new class instance. Chris@0: * Chris@0: * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler Chris@0: * The module handler. Chris@0: * @param \Drupal\Core\Cache\CacheBackendInterface $cache Chris@0: * The token cache. Chris@0: * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager Chris@0: * The language manager. Chris@0: * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator Chris@0: * The cache tags invalidator. Chris@0: * @param \Drupal\Core\Render\RendererInterface $renderer Chris@0: * The renderer. Chris@0: */ Chris@0: public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer) { Chris@0: $this->cache = $cache; Chris@0: $this->languageManager = $language_manager; Chris@0: $this->moduleHandler = $module_handler; Chris@0: $this->cacheTagsInvalidator = $cache_tags_invalidator; Chris@0: $this->renderer = $renderer; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Replaces all tokens in a given string with appropriate values. Chris@0: * Chris@0: * @param string $text Chris@0: * An HTML string containing replaceable tokens. The caller is responsible Chris@0: * for calling \Drupal\Component\Utility\Html::escape() in case the $text Chris@0: * was plain text. Chris@0: * @param array $data Chris@0: * (optional) An array of keyed objects. For simple replacement scenarios Chris@0: * 'node', 'user', and others are common keys, with an accompanying node or Chris@0: * user object being the value. Some token types, like 'site', do not require Chris@0: * any explicit information from $data and can be replaced even if it is Chris@0: * empty. Chris@0: * @param array $options Chris@0: * (optional) A keyed array of settings and flags to control the token Chris@0: * replacement process. Supported options are: Chris@0: * - langcode: A language code to be used when generating locale-sensitive Chris@0: * tokens. Chris@0: * - callback: A callback function that will be used to post-process the Chris@0: * array of token replacements after they are generated. Chris@0: * - clear: A boolean flag indicating that tokens should be removed from the Chris@0: * final text if no replacement value can be generated. Chris@0: * @param \Drupal\Core\Render\BubbleableMetadata|null $bubbleable_metadata Chris@0: * (optional) An object to which static::generate() and the hooks and Chris@0: * functions that it invokes will add their required bubbleable metadata. Chris@0: * Chris@0: * To ensure that the metadata associated with the token replacements gets Chris@0: * attached to the same render array that contains the token-replaced text, Chris@0: * callers of this method are encouraged to pass in a BubbleableMetadata Chris@0: * object and apply it to the corresponding render array. For example: Chris@0: * @code Chris@0: * $bubbleable_metadata = new BubbleableMetadata(); Chris@0: * $build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata); Chris@0: * $bubbleable_metadata->applyTo($build); Chris@0: * @endcode Chris@0: * Chris@0: * When the caller does not pass in a BubbleableMetadata object, this Chris@0: * method creates a local one, and applies the collected metadata to the Chris@0: * Renderer's currently active render context. Chris@0: * Chris@0: * @return string Chris@0: * The token result is the entered HTML text with tokens replaced. The Chris@0: * caller is responsible for choosing the right escaping / sanitization. If Chris@0: * the result is intended to be used as plain text, using Chris@0: * PlainTextOutput::renderFromHtml() is recommended. If the result is just Chris@0: * printed as part of a template relying on Twig autoescaping is possible, Chris@0: * otherwise for example the result can be put into #markup, in which case Chris@0: * it would be sanitized by Xss::filterAdmin(). Chris@0: */ Chris@0: public function replace($text, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL) { Chris@0: $text_tokens = $this->scan($text); Chris@0: if (empty($text_tokens)) { Chris@0: return $text; Chris@0: } Chris@0: Chris@0: $bubbleable_metadata_is_passed_in = (bool) $bubbleable_metadata; Chris@0: $bubbleable_metadata = $bubbleable_metadata ?: new BubbleableMetadata(); Chris@0: Chris@0: $replacements = []; Chris@0: foreach ($text_tokens as $type => $tokens) { Chris@0: $replacements += $this->generate($type, $tokens, $data, $options, $bubbleable_metadata); Chris@0: if (!empty($options['clear'])) { Chris@0: $replacements += array_fill_keys($tokens, ''); Chris@0: } Chris@0: } Chris@0: Chris@0: // Escape the tokens, unless they are explicitly markup. Chris@0: foreach ($replacements as $token => $value) { Chris@0: $replacements[$token] = $value instanceof MarkupInterface ? $value : new HtmlEscapedText($value); Chris@0: } Chris@0: Chris@0: // Optionally alter the list of replacement values. Chris@0: if (!empty($options['callback'])) { Chris@0: $function = $options['callback']; Chris@0: $function($replacements, $data, $options, $bubbleable_metadata); Chris@0: } Chris@0: Chris@0: $tokens = array_keys($replacements); Chris@0: $values = array_values($replacements); Chris@0: Chris@0: // If a local $bubbleable_metadata object was created, apply the metadata Chris@0: // it collected to the renderer's currently active render context. Chris@0: if (!$bubbleable_metadata_is_passed_in && $this->renderer->hasRenderContext()) { Chris@0: $build = []; Chris@0: $bubbleable_metadata->applyTo($build); Chris@0: $this->renderer->render($build); Chris@0: } Chris@0: Chris@0: return str_replace($tokens, $values, $text); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Builds a list of all token-like patterns that appear in the text. Chris@0: * Chris@0: * @param string $text Chris@0: * The text to be scanned for possible tokens. Chris@0: * Chris@0: * @return array Chris@0: * An associative array of discovered tokens, grouped by type. Chris@0: */ Chris@0: public function scan($text) { Chris@0: // Matches tokens with the following pattern: [$type:$name] Chris@0: // $type and $name may not contain [ ] characters. Chris@0: // $type may not contain : or whitespace characters, but $name may. Chris@0: preg_match_all('/ Chris@0: \[ # [ - pattern start Chris@0: ([^\s\[\]:]+) # match $type not containing whitespace : [ or ] Chris@0: : # : - separator Chris@0: ([^\[\]]+) # match $name not containing [ or ] Chris@0: \] # ] - pattern end Chris@0: /x', $text, $matches); Chris@0: Chris@0: $types = $matches[1]; Chris@0: $tokens = $matches[2]; Chris@0: Chris@0: // Iterate through the matches, building an associative array containing Chris@0: // $tokens grouped by $types, pointing to the version of the token found in Chris@0: // the source text. For example, $results['node']['title'] = '[node:title]'; Chris@0: $results = []; Chris@0: for ($i = 0; $i < count($tokens); $i++) { Chris@0: $results[$types[$i]][$tokens[$i]] = $matches[0][$i]; Chris@0: } Chris@0: Chris@0: return $results; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates replacement values for a list of tokens. Chris@0: * Chris@0: * @param string $type Chris@0: * The type of token being replaced. 'node', 'user', and 'date' are common. Chris@0: * @param array $tokens Chris@0: * An array of tokens to be replaced, keyed by the literal text of the token Chris@0: * as it appeared in the source text. Chris@0: * @param array $data Chris@0: * An array of keyed objects. For simple replacement scenarios: 'node', Chris@0: * 'user', and others are common keys, with an accompanying node or user Chris@0: * object being the value. Some token types, like 'site', do not require Chris@0: * any explicit information from $data and can be replaced even if it is Chris@0: * empty. Chris@0: * @param array $options Chris@0: * A keyed array of settings and flags to control the token replacement Chris@0: * process. Supported options are: Chris@0: * - langcode: A language code to be used when generating locale-sensitive Chris@0: * tokens. Chris@0: * - callback: A callback function that will be used to post-process the Chris@0: * array of token replacements after they are generated. Can be used when Chris@0: * modules require special formatting of token text, for example URL Chris@0: * encoding or truncation to a specific length. Chris@0: * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata Chris@0: * The bubbleable metadata. This is passed to the token replacement Chris@0: * implementations so that they can attach their metadata. Chris@0: * Chris@0: * @return array Chris@0: * An associative array of replacement values, keyed by the original 'raw' Chris@0: * tokens that were found in the source text. For example: Chris@0: * $results['[node:title]'] = 'My new node'; Chris@0: * Chris@0: * @see hook_tokens() Chris@0: * @see hook_tokens_alter() Chris@0: */ Chris@0: public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { Chris@0: foreach ($data as $object) { Chris@0: if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) { Chris@0: $bubbleable_metadata->addCacheableDependency($object); Chris@0: } Chris@0: } Chris@0: Chris@0: $replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]); Chris@0: Chris@0: // Allow other modules to alter the replacements. Chris@0: $context = [ Chris@0: 'type' => $type, Chris@0: 'tokens' => $tokens, Chris@0: 'data' => $data, Chris@0: 'options' => $options, Chris@0: ]; Chris@0: $this->moduleHandler->alter('tokens', $replacements, $context, $bubbleable_metadata); Chris@0: Chris@0: return $replacements; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a list of tokens that begin with a specific prefix. Chris@0: * Chris@0: * Used to extract a group of 'chained' tokens (such as [node:author:name]) Chris@0: * from the full list of tokens found in text. For example: Chris@0: * @code Chris@0: * $data = array( Chris@0: * 'author:name' => '[node:author:name]', Chris@0: * 'title' => '[node:title]', Chris@0: * 'created' => '[node:created]', Chris@0: * ); Chris@0: * $results = Token::findWithPrefix($data, 'author'); Chris@0: * $results == array('name' => '[node:author:name]'); Chris@0: * @endcode Chris@0: * Chris@0: * @param array $tokens Chris@0: * A keyed array of tokens, and their original raw form in the source text. Chris@0: * @param string $prefix Chris@0: * A textual string to be matched at the beginning of the token. Chris@0: * @param string $delimiter Chris@0: * (optional) A string containing the character that separates the prefix from Chris@0: * the rest of the token. Defaults to ':'. Chris@0: * Chris@0: * @return array Chris@0: * An associative array of discovered tokens, with the prefix and delimiter Chris@0: * stripped from the key. Chris@0: */ Chris@0: public function findWithPrefix(array $tokens, $prefix, $delimiter = ':') { Chris@0: $results = []; Chris@0: foreach ($tokens as $token => $raw) { Chris@0: $parts = explode($delimiter, $token, 2); Chris@0: if (count($parts) == 2 && $parts[0] == $prefix) { Chris@0: $results[$parts[1]] = $raw; Chris@0: } Chris@0: } Chris@0: return $results; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns metadata describing supported tokens. Chris@0: * Chris@0: * The metadata array contains token type, name, and description data as well Chris@0: * as an optional pointer indicating that the token chains to another set of Chris@0: * tokens. Chris@0: * Chris@0: * @return array Chris@0: * An associative array of token information, grouped by token type. The Chris@0: * array structure is identical to that of hook_token_info(). Chris@0: * Chris@0: * @see hook_token_info() Chris@0: */ Chris@0: public function getInfo() { Chris@0: if (is_null($this->tokenInfo)) { Chris@0: $cache_id = 'token_info:' . $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId(); Chris@0: $cache = $this->cache->get($cache_id); Chris@0: if ($cache) { Chris@0: $this->tokenInfo = $cache->data; Chris@0: } Chris@0: else { Chris@0: $this->tokenInfo = $this->moduleHandler->invokeAll('token_info'); Chris@0: $this->moduleHandler->alter('token_info', $this->tokenInfo); Chris@0: $this->cache->set($cache_id, $this->tokenInfo, CacheBackendInterface::CACHE_PERMANENT, [ Chris@0: static::TOKEN_INFO_CACHE_TAG, Chris@0: ]); Chris@0: } Chris@0: } Chris@0: Chris@0: return $this->tokenInfo; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets metadata describing supported tokens. Chris@0: * Chris@0: * @param array $tokens Chris@0: * Token metadata that has an identical structure to the return value of Chris@0: * hook_token_info(). Chris@0: * Chris@0: * @see hook_token_info() Chris@0: */ Chris@0: public function setInfo(array $tokens) { Chris@0: $this->tokenInfo = $tokens; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Resets metadata describing supported tokens. Chris@0: */ Chris@0: public function resetInfo() { Chris@0: $this->tokenInfo = NULL; Chris@0: $this->cacheTagsInvalidator->invalidateTags([static::TOKEN_INFO_CACHE_TAG]); Chris@0: } Chris@0: Chris@0: }