View source
<?php
namespace Drupal\metatag;
use Drupal\Core\Utility\Token;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\token\TokenEntityMapperInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class MetatagToken {
use StringTranslationTrait;
protected $token;
protected $tokenEntityMapper;
public function __construct(Token $token, TokenEntityMapperInterface $token_entity_mapper) {
$this->token = $token;
$this->tokenEntityMapper = $token_entity_mapper;
}
public function replace($string, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
$options = $options + [
'clear' => TRUE,
];
$replaced = $this->token
->replace($string, $data, $options, $bubbleable_metadata);
$replaced = preg_replace('/(?<!:)(?<!)\\/+\\//', '/', $replaced);
return $replaced;
}
public function tokenBrowser(array $token_types = [], $image_help = FALSE) {
$form = [];
$form['intro_text'] = [
'#markup' => '<p>' . $this
->t('Use tokens to avoid redundant meta data and search engine penalization. For example, a \'keyword\' value of "example" will be shown on all content using this configuration, whereas using the [node:field_keywords] automatically inserts the "keywords" values from the current entity (node, term, etc).') . '</p>',
'#weight' => -10,
];
if ($image_help) {
$form['image_help'] = [
'#markup' => '<p>' . $this
->t('To use tokens to image fields, the image field on that entity bundle (content type, term, etc) must have the "Token" display settings enabled, the image field must not be hidden, and it must be set to output as an image, e.g. using the "Thumbnail" field formatter. It is also recommended to use an appropriate image style that resizes the image rather than output the original image; see individual meta tag descriptions for size recommendations.') . '</strong></p>',
'#weight' => -9,
];
}
if (!empty($token_types)) {
$token_types = array_map(function ($value) {
return $this->tokenEntityMapper
->getTokenTypeForEntityType($value, TRUE);
}, $token_types);
}
$form['tokens'] = [
'#theme' => 'token_tree_link',
'#token_types' => $token_types,
'#global_types' => TRUE,
'#show_nested' => FALSE,
];
return $form;
}
}