cache_url_query_ignore-1.0.0-rc1/src/Cache/Context/UrlQueryIgnoreCacheContext.php

src/Cache/Context/UrlQueryIgnoreCacheContext.php
<?php

declare(strict_types=1);

namespace Drupal\cache_url_query_ignore\Cache\Context;

use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Cache\Context\UrlCacheContext;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ImmutableConfig;

/**
 * Decorates the UrlCacheContext service.
 *
 * Cache context ID: 'url'.
 */
final class UrlQueryIgnoreCacheContext {

  /**
   * The module config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Cache\Context\UrlCacheContext $inner
   *   The Url Cache Context to decorate.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(protected UrlCacheContext $inner, ConfigFactoryInterface $config_factory) {
    $this->config = $config_factory->get('cache_url_query_ignore.settings');
  }

  /**
   * Returns the string representation of the cache context.
   *
   * A cache context service's name is used as a token (placeholder) cache key,
   * and is then replaced with the string returned by this method.
   *
   * @return string
   *   The string representation of the cache context.
   */
  public function getContext(): string {
    return $this->clean($this->inner->getContext());
  }

  /**
   * Clear query string.
   *
   * @param string $value
   *   The value to clean-up.
   *
   * @return string
   *   The cleared value.
   */
  private function clean(string $value): string {

    $request_parts = UrlHelper::parse($value);
    if (empty($request_parts['query'])) {
      return $value;
    }

    $request_uri = $request_parts['path'] ?? '';

    $params = array_map('trim', explode("\n", $this->config->get('query_parameters')));
    if ($this->config->get('ignore_action') === 'include') {
      $keep = array_flip($params);
      $request_query = array_intersect_key($request_parts['query'], $keep);
    }
    else {
      $request_query = UrlHelper::filterQueryParameters($request_parts['query'], $params);
    }

    if (!empty($request_query)) {
      $request_uri .= '?' . UrlHelper::buildQuery($request_query);
    }

    return $request_uri;
  }

}

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

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