Version 1
[yaffs-website] / web / modules / contrib / metatag / src / MetatagToken.php
1 <?php
2
3 namespace Drupal\metatag;
4 use Drupal\Core\Utility\Token;
5
6 /**
7  * Token handling service. Uses core token service or contributed Token.
8  */
9 class MetatagToken {
10
11   /**
12    * Token service.
13    *
14    * @var \Drupal\Core\Utility\Token
15    */
16   protected $token;
17
18   /**
19    * Constructs a new MetatagToken object.
20    *
21    * @param \Drupal\Core\Utility\Token $token
22    *   Token service.
23    */
24   public function __construct(Token $token) {
25     $this->token = $token;
26   }
27
28   /**
29    * Wrapper for the Token module's string parsing.
30    *
31    * @param $string
32    * @param $data
33    * @param array $options
34    *
35    * @return mixed|string $string
36    */
37   public function replace($string, $data, $options = []) {
38     $options['clear'] = TRUE;
39
40     $replaced = $this->token->replace($string, $data, $options);
41
42     // Ensure that there are no double-slash sequences due to empty token
43     // values.
44     $replaced = preg_replace('/(?<!:)\/+\//', '/', $replaced);
45
46     return $replaced;
47   }
48
49   /**
50    * Gatekeeper function to direct to either the core or contributed Token.
51    *
52    * @param array $token_types
53    *   The token types to filter the tokens list by. Defaults to an empty array.
54    *
55    * @return array
56    *   If token module is installed, a popup browser plus a help text. If not
57    *   only the help text.
58    */
59   public function tokenBrowser(array $token_types = []) {
60     $form = [];
61
62     $form['intro_text'] = [
63       '#markup' => '<p>' . t('Configure the meta tags below. 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>',
64     ];
65
66     // Normalize taxonomy tokens.
67     if (!empty($token_types)) {
68       $token_types = array_map(function($value) {
69         return stripos($value, 'taxonomy_') === 0 ? substr($value, strlen('taoxnomy_')) : $value;
70       }, (array) $token_types);
71     }
72
73     $form['tokens'] = [
74       '#theme' => 'token_tree_link',
75       '#token_types' => $token_types,
76       '#global_types' => TRUE,
77       '#show_nested' => FALSE,
78     ];
79
80     return $form;
81   }
82
83 }