You are here

message_banner.module in Message Banner 8

Main module file for the Message Banner module.

File

message_banner.module
View source
<?php

/**
 * @file
 * Main module file for the Message Banner module.
 */
use Drupal\Core\Cache\Cache;

/**
 * Implements hook_theme().
 */
function message_banner_theme(array $existing, $type, $theme, $path) : array {
  return [
    'message_banner' => [
      'variables' => [
        'message' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_page_attachments().
 */
function message_banner_page_attachments(array &$attachments) {
  $config = Drupal::config('message_banner.settings');

  // Don't display the banner on admin routes.
  if (!$config
    ->get('banner_enabled_on_admin_routes')) {
    if (Drupal::service('router.admin_context')
      ->isAdminRoute()) {
      return;
    }
  }

  // Don't attach to the page if the banner isn't enabled.
  if (!$config
    ->get('banner_enabled')) {
    return;
  }
  $message = [
    '#theme' => 'message_banner',
    '#message' => check_markup($config
      ->get('banner_text.value'), $config
      ->get('banner_text.format')),
    '#cache' => [
      'contexts' => [
        'user.roles',
      ],
    ],
  ];
  $user_storage = Drupal::entityTypeManager()
    ->getStorage('user');
  $user = $user_storage
    ->load(Drupal::currentUser()
    ->id());
  if ($user
    ->hasPermission('view message banner')) {

    // Render the message, so it can be directly output in the JavaScript.
    $message = Drupal::service('renderer')
      ->renderRoot($message)
      ->__toString();
    $drupal_settings = [
      'banner_text' => $message,
      'banner_timestamp' => Drupal::state()
        ->get('banner_saved'),
      'banner_show_again_minutes' => $config
        ->get('banner_show_again_minutes') ?: 0,
    ];
    $attachments['#attached']['drupalSettings']['messageBanner'] = $drupal_settings;
    $attachments['#attached']['library'][] = 'message_banner/message_banner';
    $cache_tags = $attachments['#cache']['tags'] ?? [];
    $attachments['#cache']['tags'] = Cache::mergeTags($cache_tags, $config
      ->getCacheTags());
  }
}

/**
 * Implements template_preprocess_HOOK().
 */
function template_preprocess_message_banner(array &$variables) {
  $variables['attributes']['id'] = 'message-banner';
  $variables['attributes']['class'][] = 'message-banner';

  // Add the banner color as a class.
  $config = Drupal::config('message_banner.settings');
  $variables['attributes']['class'][] = $config
    ->get('banner_color');
}

Functions

Namesort descending Description
message_banner_page_attachments Implements hook_page_attachments().
message_banner_theme Implements hook_theme().
template_preprocess_message_banner Implements template_preprocess_HOOK().