node_singles-3.0.2/node_singles.tokens.inc
node_singles.tokens.inc
<?php
/**
* @file
* Tokens for the node singles module.
*/
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\node\NodeInterface;
use Drupal\node\NodeTypeInterface;
/**
* Implements @see hook_token_info().
*/
function node_singles_token_info(): array {
$types = [];
$types['node_singles'] = [
'name' => t('Node Singles'),
'description' => t('Node Singles tokens'),
];
$tokens = [];
foreach (\Drupal::service('node_singles')->getAllSingles() as $type) {
assert($type instanceof NodeTypeInterface);
$tokens['node_singles'][$type->id()] = [
'name' => $type->label(),
'description' => t('Field values from the single entity.'),
'type' => 'node',
];
}
return [
'types' => $types,
'tokens' => $tokens,
];
}
/**
* Implements @see hook_tokens().
*/
function node_singles_tokens(string $type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleableMetadata): array {
$replacements = [];
if ($type !== 'node_singles') {
return $replacements;
}
/** @var \Drupal\node_singles\Service\NodeSinglesInterface $singles */
$singles = \Drupal::service('node_singles');
/** @var \Drupal\path_alias\AliasManagerInterface $pathAliasManager */
$pathAliasManager = \Drupal::service('path_alias.manager');
foreach ($tokens as $name => $original) {
[$singleName, $subType] = explode(':', $name);
$node = $singles->getSingleByBundle($singleName);
if (!$node instanceof NodeInterface) {
continue;
}
if ($subType === 'url') {
$canonical = '/node/' . $node->id();
$alias = $pathAliasManager->getAliasByPath($canonical, $options['langcode'] ?? NULL);
if ($alias !== $canonical) {
$replacements[$original] = $alias;
}
continue;
}
if ($entityTokens = \Drupal::token()->findWithPrefix($tokens, $singleName)) {
$replacements += \Drupal::token()->generate('node', $entityTokens, ['node' => $node], $options, $bubbleableMetadata);
}
}
return $replacements;
}
