You are here

function language_access_page_attachments_alter in Language access 8

Implements hook_page_attachments_alter().

Hide hreflang tags for translations the current user doesn't have access to.

File

./language_access.module, line 82
Provide access permissions by language.

Code

function language_access_page_attachments_alter(array &$attachments) {
  if (isset($attachments['#attached']['html_head_link'])) {
    $languages = \Drupal::languageManager()
      ->getLanguages();
    foreach ($attachments['#attached']['html_head_link'] as $key => $html_head_link) {

      // Check that we're altering the right tag.
      if (!isset($html_head_link[0]['rel'], $html_head_link[0]['hreflang']) || $html_head_link[0]['rel'] !== 'alternate') {
        continue;
      }

      // Check that the language exists.
      if (!isset($languages[$html_head_link[0]['hreflang']])) {
        continue;
      }

      // Check that the user doesn't have access to the language.
      if (\Drupal::currentUser()
        ->hasPermission('access language ' . $html_head_link[0]['hreflang'])) {
        continue;
      }
      unset($attachments['#attached']['html_head_link'][$key]);
    }
  }
}