You are here

function adsense_page_attachments in Google AdSense integration 8

Implements hook_page_attachments().

File

./adsense.module, line 19
Displays Google AdSense ads on Drupal pages.

Code

function adsense_page_attachments(array &$attachments) {
  $config = \Drupal::config('adsense.settings');
  if ($config
    ->get('adsense_managed_page_level_ads_enabled')) {

    /** @var \Drupal\system\Plugin\Condition\RequestPath $condition */
    $condition = \Drupal::getContainer()
      ->get('plugin.manager.condition')
      ->createInstance('request_path');
    $visibility = $config
      ->get('adsense_access_pages');
    if ($visibility) {
      $condition
        ->setConfiguration($visibility);
    }
    if ($visibility['negate'] xor !$condition
      ->evaluate()) {
      $attachments['#attached']['html_head'][] = [
        [
          '#type' => 'inline_template',
          '#template' => '<!-- adsense auto ads: {{ comment }} -->',
          '#context' => [
            'comment' => 'page not in match list',
          ],
        ],
        'adsense_unmatched_page',
      ];
    }
    elseif (AdsenseAdBase::isDisabled()) {
      $attachments['#attached']['html_head'][] = [
        [
          '#type' => 'inline_template',
          '#template' => '<!-- adsense auto ads: {{ comment }} -->',
          '#context' => [
            'comment' => 'ads disabled',
          ],
        ],
        'adsense_ads_disabled',
      ];
    }
    else {
      $client = PublisherId::get();
      \Drupal::moduleHandler()
        ->alter('adsense', $client);
      $attachments['#attached']['html_head'][] = [
        [
          '#type' => 'inline_template',
          '#template' => '',
          '#theme' => 'adsense_managed_page_level',
          '#client' => $client,
        ],
        'adsense_managed_page_level',
      ];
    }
  }
}