FlexiformTreeBuilder.php in Flexiform 8
File
src/FlexiformTreeBuilder.php
View source
<?php
namespace Drupal\flexiform;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Utility\Token;
use Drupal\token\TreeBuilder;
class FlexiformTreeBuilder extends TreeBuilder {
public function buildTree($token_type, array $options = []) {
$options += [
'restricted' => FALSE,
'depth' => 4,
'data' => [],
'values' => FALSE,
'flat' => FALSE,
];
$options['depth'] = min($options['depth'], static::MAX_DEPTH);
if ($entity_token_type = $this->entityMapper
->getTokenTypeForEntityType($token_type)) {
$token_type = $entity_token_type;
}
$langcode = $this->languageManager
->getCurrentLanguage()
->getId();
$tree_cid = "token_tree:{$token_type}:{$langcode}:{$options['depth']}";
if (!isset($this->builtTrees[$tree_cid])) {
if ($cache = $this->cacheBackend
->get($tree_cid)) {
$this->builtTrees[$tree_cid] = $cache->data;
}
else {
if (empty($options['parents'])) {
$options['parents'] = [];
}
$this->builtTrees[$tree_cid] = $this
->getTokenData($token_type, $options);
$this->cacheBackend
->set($tree_cid, $this->builtTrees[$tree_cid], Cache::PERMANENT, [
Token::TOKEN_INFO_CACHE_TAG,
]);
}
}
$tree = $this->builtTrees[$tree_cid];
if (!empty($options['flat'])) {
$tree = $this
->flattenTree($tree);
}
if (!empty($options['values'])) {
$token_values = [];
foreach ($tree as $token => $token_info) {
if (!empty($token_info['dynamic']) || !empty($token_info['restricted'])) {
continue;
}
elseif (!isset($token_info['value'])) {
$token_values[$token_info['token']] = $token;
}
}
if (!empty($token_values)) {
$token_values = $this->tokenService
->generate($token_type, $token_values, $options['data'], [], new BubbleableMetadata());
foreach ($token_values as $token => $replacement) {
$tree[$token]['value'] = $replacement;
}
}
}
return $tree;
}
}