You are here

function message_banner_page_attachments in Message Banner 8

Implements hook_page_attachments().

File

./message_banner.module, line 26
Main module file for the Message Banner module.

Code

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());
  }
}