You are here

resource_hints.module in Resource Hints 8

Same filename and directory in other branches
  1. 7.2 resource_hints.module
  2. 7 resource_hints.module

Module hooks for the resource hints module.

File

resource_hints.module
View source
<?php

/**
 * @file
 * Module hooks for the resource hints module.
 */
use Drupal\Component\Utility\UrlHelper;
use Drupal\resource_hints\Form\ResourceHintsConfigForm;
use Drupal\Component\Utility\Html;

/**
 * Implements hook_page_attachments_alter().
 */
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;
    }
  }
}