function background_image_tokens in Background Image 8
Same name and namespace in other branches
- 2.x background_image.module \background_image_tokens()
- 2.0.x background_image.module \background_image_tokens()
Implements hook_tokens().
File
- ./
background_image.module, line 181 - Background Image module's procedural hooks and functions.
Code
function background_image_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$token = \Drupal::token();
$replacements = [];
// [*:background_image:image:*] chained tokens.
// Note: this is primarily to deal with parent background images.
$entityType = 'background_image';
$fieldName = 'image';
if ($type === 'entity' && !empty($data['entity_type']) && $data['entity_type'] === $entityType && !empty($data['entity']) && !empty($data['token_type']) && ($fieldTokens = $token
->findWithPrefix($tokens, $fieldName))) {
/** @var \Drupal\background_image\BackgroundImageInterface $backgroundImage */
$backgroundImage = $data['entity'];
$field = $backgroundImage
->get($fieldName);
// If there's an image value, it will be used and can be handled by the
// token module normally.
if (!$field
->isEmpty()) {
return [];
}
// Otherwise, the parent background image value needs to be supplied.
while ($field
->isEmpty()) {
if (!($backgroundImage = $backgroundImage
->getParent())) {
return $replacements;
}
$field = $backgroundImage
->get($fieldName);
}
// If there are still no more
if ($field && !$field
->isEmpty()) {
$property_token_data = [
'field_property' => TRUE,
"{$entityType}-{$fieldName}" => $field,
'field_name' => "{$entityType}-{$fieldName}",
];
$replacements += $token
->generate($fieldName, $fieldTokens, $property_token_data, $options, $bubbleable_metadata);
}
return $replacements;
}
// [*:background_image:*] chained tokens.
$backgroundImageTokens = $token
->findWithPrefix($tokens, $entityType);
if ($backgroundImageTokens && _token_module($type, $entityType) === $entityType) {
$backgroundImage = FALSE;
$manager = BackgroundImageManager::service();
if ($type === 'current-page') {
$backgroundImage = $manager
->getBackgroundImage();
}
elseif ($type === 'site') {
$backgroundImage = $manager
->getGlobalBackgroundImage() ?: FALSE;
}
elseif ($entity = isset($data[$type]) ? $data[$type] : NULL) {
if ($entity instanceof EntityInterface && ($bgImg = $manager
->getEntityBackgroundImage($entity))) {
$backgroundImage = $bgImg;
}
elseif ($entity instanceof ViewEntityInterface && ($bgImg = $manager
->getViewBackgroundImage($entity))) {
$backgroundImage = $bgImg;
}
else {
$backgroundImage = $manager
->getGlobalBackgroundImage() ?: FALSE;
}
}
if ($backgroundImage) {
$replacements += $token
->generate($entityType, $backgroundImageTokens, [
$entityType => $backgroundImage,
], $options, $bubbleable_metadata);
}
}
return $replacements;
}