You are here

function fontscom_api_page_attachments in @font-your-face 8.3

Implements hook_page_attachments().

File

modules/fontscom_api/fontscom_api.module, line 132
Fonts.com API module file.

Code

function fontscom_api_page_attachments(&$page) {
  $config = \Drupal::config('fontscom_api.settings');

  // Only get all fonts when we have set a project and token.
  if (!empty($config
    ->get('token')) && !empty($config
    ->get('project'))) {
    $page['#attached']['html_head'][] = [
      [
        '#type' => 'html_tag',
        '#tag' => 'script',
        '#attributes' => [
          'src' => 'https://fast.fonts.net/jsapi/' . $config
            ->get('project') . '.js',
        ],
      ],
      'fontyourface-fontscom-api-' . $config
        ->get('project'),
    ];
  }
  $enabled_fonts =& drupal_static('fontyourface_fonts', []);
  $font_css = '';
  foreach ($enabled_fonts as $font) {
    if ($font->pid->value == 'fontscom_api') {
      if ($font
        ->isDeactivated()) {
        $font_css .= _fontscom_api_generate_font_css($font);
      }
    }
  }
  if (!empty($font_css)) {
    $hash = hash('sha256', $font_css);
    $directory_location = 'fontyourface/fontscom_api';
    \Drupal::service('file_system')
      ->prepareDirectory($directory_location, FileSystemInterface::CREATE_DIRECTORY);
    if (!file_exists($directory_location . '/fontyourface-stylesheet-' . $hash . '.css')) {
      \Drupal::service('file_system')
        ->saveData($font_css, $directory_location . '/fontyourface-stylesheet-' . $hash . '.css', FileSystemInterface::EXISTS_REPLACE);
    }
    $page['#attached']['html_head'][] = [
      [
        '#type' => 'html_tag',
        '#tag' => 'link',
        '#attributes' => [
          'rel' => 'stylesheet',
          'href' => file_create_url($directory_location . '/fontyourface-stylesheet-' . $hash . '.css'),
          'media' => 'all',
        ],
      ],
      'fontyourface-fontscom-api-preview-fonts',
    ];
  }
}