usfedgov_google_analytics-8.x-1.2/src/Hook/PageAttachments.php

src/Hook/PageAttachments.php
<?php

namespace Drupal\usfedgov_google_analytics\Hook;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Routing\AdminContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountProxy;

/**
 * Attaches DAP JavaScript to pages.
 */
class PageAttachments {

  /**
   * Routes to which the JavaScript should not be attached.
   */
  const INVALID_ROUTES = [
    'user.login',
    'user.logout',
    'user.pass',
  ];

  public function __construct(
    protected ConfigFactoryInterface $configFactory,
    protected AccountProxy $currentUser,
    protected RouteMatchInterface $routeMatch,
    protected AdminContext $adminContext,
  ) {}

  /**
   * Implements hook_page_attachments().
   *
   * Attaches the DAP JavaScript to pages.
   *
   * Don't attach the JS if:
   *   - Tracking is disabled
   *   - There is no agency configured
   *   - The current user is authenticated
   *   - The page is one of the invalid routes
   *   - The page is an admin route.
   *
   * @return bool
   *   TRUE if the JavaScript should be attached, FALSE if one of the conditions
   *   for not attaching was met. This is done for the sake of testing to make
   *   it easy to know what the result is.
   */
  #[Hook('page_attachments')]
  public function attachJavascript(array &$page) {
    $config = $this->configFactory->get('usfedgov_google_analytics.settings');

    if (
      !$config->get('status')
      || empty($config->get('query_parameters.agency'))
      || $this->currentUser->isAuthenticated()
      || in_array($this->routeMatch->getRouteName(), self::INVALID_ROUTES)
      || $this->adminContext->isAdminRoute()
    ) {
      return FALSE;
    }

    $page['#attached']['library'][] = 'usfedgov_google_analytics/usfedgov_google_analytics.' . $config->get('library');

    // Adding a cache tag for the settings causes cached pages with the JS
    // attached to be invalidated automatically when the settings are updated.
    $page['#cache']['tags'][] = 'config:usfedgov_google_analytics.settings';
    return TRUE;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc