You are here

background_image.module in Background Image 2.0.x

Same filename and directory in other branches
  1. 8 background_image.module
  2. 2.x background_image.module

Background Image module's procedural hooks and functions.

File

background_image.module
View source
<?php

/**
 * @file
 * Background Image module's procedural hooks and functions.
 */
use Drupal\background_image\BackgroundImageInterface;
use Drupal\background_image\BackgroundImageManager;
use Drupal\background_image\Form\BackgroundImageForm;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\views\ViewEntityInterface;

/**
 * Implements hook_cache_flush().
 */
function background_image_cache_flush() {
  BackgroundImageManager::service()
    ->cacheFlush();
}

/**
 * Implements hook_module_implements_alter().
 *
 * {@inheritdoc}
 */
function background_image_module_implements_alter(&$implementations, $hook) {
  if (($hook == 'tokens_alter' || $hook == 'token_info_alter') && isset($implementations['background_image'])) {
    $group = $implementations['background_image'];
    unset($implementations['background_image']);
    $implementations['background_image'] = $group;
  }
}

/**
 * Implements hook_entity_delete().
 *
 * {@inheritdoc}
 */
function background_image_entity_delete(EntityInterface $entity) {
  if ($background_image = BackgroundImageManager::service()
    ->getEntityBackgroundImage($entity)) {
    $background_image
      ->delete();
  }
}

/**
 * Implements hook_entity_prepare_form().
 *
 * {@inheritdoc}
 */
function background_image_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {
  BackgroundImageManager::service()
    ->prepareEntityForm($entity, $operation, $form_state);
}

/**
 * Implements hook_form_alter().
 *
 * {@inheritdoc}
 */
function background_image_form_alter(array &$form, FormStateInterface $form_state) {
  BackgroundImageManager::service()
    ->alterEntityForm($form, $form_state);
}

/**
 * Implements hook_inline_entity_form_entity_form_alter().
 *
 * {@inheritdoc}
 */
function background_image_inline_entity_form_entity_form_alter(&$entity_form, FormStateInterface $form_state) {
  $entity = $entity_form['#entity'];
  if ($entity instanceof BackgroundImageInterface) {
    BackgroundImageForm::create($entity, $form_state
      ->getCompleteForm(), $form_state, $entity_form)
      ->build();
  }
}

/**
 * Implements hook_preprocess_HOOK().
 *
 * {@inheritdoc}
 */
function background_image_preprocess_region__background_image(&$variables) {
  $variables['base_class'] = BackgroundImageManager::service()
    ->getBaseClass();
}

/**
 * Implements hook_preprocess_HOOK().
 *
 * {@inheritdoc}
 */
function background_image_preprocess_html(&$variables) {
  $manager = BackgroundImageManager::service();
  if ($background_image = $manager
    ->getBackgroundImage()) {
    $base_class = $manager
      ->getBaseClass();
    if ($background_image
      ->getSetting('dark')) {
      $variables['attributes']['class'][] = "{$base_class}-dark";
    }
    if ($background_image
      ->getSetting('full_viewport')) {
      $variables['attributes']['class'][] = "{$base_class}-full-viewport";
    }
  }
  $variables['#cache']['context'][] = 'background_image.settings.dark';
  $variables['#cache']['context'][] = 'background_image.settings.full_viewport';
}

/**
 * Implements hook_system_info_alter().
 *
 * {@inheritdoc}
 */
function background_image_system_info_alter(&$info, Extension $file, $type) {

  // Inject a "Background Image" region for all themes.
  if ($type == 'theme') {
    $info['regions'] = [
      'background_image' => 'Background Image',
    ] + $info['regions'];
  }
}

/**
 * Implements hook_theme().
 *
 * {@inheritdoc}
 */
function background_image_theme($existing, $type, $theme, $path) {
  $module_path = drupal_get_path('module', 'background_image');
  $hooks['container__background_image'] = [
    'base hook' => 'container',
    'path' => "{$module_path}/templates",
    'type' => 'module',
  ];
  $hooks['region__background_image'] = [
    'base hook' => 'region',
    'path' => "{$module_path}/templates",
    'type' => 'module',
  ];
  return $hooks;
}

/**
 * Implements hook_token_info().
 */
function background_image_token_info() {
  $info['types']['background_image'] = [
    'name' => t('Background Image'),
    'description' => t('Tokens related to individual background images.'),
    'needs-data' => 'background_image',
  ];
  return $info;
}

/**
 * Implements hook_token_info_alter().
 */
function background_image_token_info_alter(&$data) {
  $types = array_map(function (EntityTypeInterface $entityType) {
    return $entityType
      ->id();
  }, BackgroundImageManager::service()
    ->getEnabledEntityTypes()) + [
    'current-page',
    'site',
  ];

  // Modify description of node tokens for our site.
  foreach ($types as $type) {

    // Skip tokens that don't exist.
    if (!isset($data['tokens'][$type])) {
      continue;
    }
    $data['tokens'][$type]['background_image'] = [
      'name' => t('Background Image'),
      'description' => t('The background image.'),
      'type' => 'background_image',
      'module' => 'background_image',
    ];
  }
}

/**
 * Implements hook_tokens().
 *
 * {@inheritdoc}
 */
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;
}