function addtocal_tokens in Add to Cal 8.2
Same name and namespace in other branches
- 7 addtocal.tokens.inc \addtocal_tokens()
Implements hook_tokens().
File
- ./
addtocal.module, line 134
Code
function addtocal_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = [];
foreach ($tokens as $name => $original) {
if (preg_match('/^(?:([\\d]+):)?addtocal-url(?::([\\w-]+))?$/i', $name, $matches)) {
$delta = $matches[1] ?: 0;
$generator_type = $matches[2] ?: '';
$token_name = $data['field_name'];
$items = $data[$token_name];
$token_name_parts = explode('-', $token_name);
$field_name = $token_name_parts[1] ?? '';
if (!$items instanceof FieldItemListInterface) {
return $replacements;
}
$entity = $items
->getEntity();
if (!$entity
->hasField($field_name) || $entity
->get($field_name)
->isEmpty()) {
return $replacements;
}
$view_mode_name = $entity
->getEntityTypeId() . '.' . $entity
->bundle() . '.token';
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
$view_display = \Drupal::entityTypeManager()
->getStorage('entity_view_display')
->load($view_mode_name);
if (empty($view_display) || !$view_display
->status()) {
$view_mode_name = $entity
->getEntityTypeId() . '.' . $entity
->bundle() . '.default';
$view_display = \Drupal::entityTypeManager()
->getStorage('entity_view_display')
->load($view_mode_name);
}
// Pull addtocal configuration from the field if it exists.
$display_options = $view_display
->getComponent($field_name);
if ($display_options['type'] != 'addtocal_view') {
$display_options = [
'type' => 'addtocal_view',
'label' => 'hidden',
];
}
$build = $entity->{$field_name}
->view($display_options);
$addtocal = $build[$delta]['addtocal'] ?? [];
$addtocal_access = !isset($addtocal['#access']) || $addtocal['#access'];
$addtocal_link = $addtocal['#addtocal_link'] ?? NULL;
$addtocal_items = $addtocal['#items'] ?? [];
$addtocal_item = $addtocal_items[$generator_type] ?? reset($addtocal_items);
$generator = $addtocal_item['generator'] ?? NULL;
if ($addtocal_access && $addtocal_link && $generator) {
$replacements[$original] = $addtocal_link
->formatWith($generator);
}
else {
$replacements[$original] = '';
}
}
}
return $replacements;
}