You are here

function resource_hints_page_attachments_alter in Resource Hints 8

Implements hook_page_attachments_alter().

File

./resource_hints.module, line 15
Module hooks for the resource hints module.

Code

function resource_hints_page_attachments_alter(array &$attachments) {
  $config = \Drupal::config('resource_hints.settings');
  $hint_types = [
    'dns-prefetch' => 'dns_prefetch',
    'preconnect' => 'preconnect',
    'prefetch' => 'prefetch',
    'prerender' => 'prerender',
  ];
  $headers = [];
  $elements = [];
  $dns_prefetch_control = Html::escape($config
    ->get('dns_prefetch_control'));
  $dns_prefetch_output = $config
    ->get('dns_prefetch_output');
  if ($dns_prefetch_output == ResourceHintsConfigForm::OUTPUT_LINK_HEADER) {
    $headers[] = [
      'X-DNS-Prefetch-Control',
      $dns_prefetch_control,
    ];
  }
  else {
    $attachments['#attached']['html_head'][] = [
      [
        '#tag' => 'meta',
        '#attributes' => [
          'http-equiv' => 'x-dns-prefetch-control',
          'content' => $dns_prefetch_control,
        ],
      ],
      'x-dns-prefetch-control',
    ];
  }
  foreach ($hint_types as $rel => $setting) {
    if ($rel == 'dns-prefetch' && $dns_prefetch_control != ResourceHintsConfigForm::DNS_PREFETCH_ENABLED) {
      continue;
    }
    $resources = $config
      ->get("{$setting}_resources") ?: [];
    $output = $config
      ->get("{$setting}_output");
    foreach ($resources as $value) {
      $value = UrlHelper::stripDangerousProtocols(trim($value));
      if ($value) {
        if ($output === ResourceHintsConfigForm::OUTPUT_LINK_HEADER) {
          $headers[] = [
            'Link',
            "<{$value}>; rel=\"{$rel}\"",
          ];
        }
        else {
          $elements[] = [
            [
              'rel' => $rel,
              'href' => $value,
            ],
          ];
        }
      }
    }
  }
  if ($headers) {
    foreach ($headers as $header) {
      $attachments['#attached']['http_header'][] = $header;
    }
  }
  if ($elements) {
    foreach ($elements as $element) {
      $attachments['#attached']['html_head_link'][] = $element;
    }
  }
}