visitors date range Cache Context

Created on 26 March 2025, 29 days ago

Problem/Motivation

Steps to reproduce

Proposed resolution

namespace Drupal\visitors\Cache;

use Drupal\Core\Cache\CacheContextInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines a custom cache context for Views, depending on TempStore date range.
 */
class DateRangeCacheContext implements CacheContextInterface {

  /**
   * The date range service.
   *
   * @var \Drupal\visitors\VisitorsDateRangeInterface
   */
  protected $dateRange;

  /**
   * Constructs a DateRangeCacheContext object.
   *
   * @param \Drupal\visitors\VisitorsDateRangeInterface $visitors_date_range
   *   The date range service.
   */
  public function __construct(VisitorsDateRangeInterface $visitors_date_range) {
    $this->dateRange = $visitors_date_range
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Visitors Date Range Filter');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    $start = $this->dateRange->getStartTimestamp();
    $end = $this->dateRange->getEndTimestamp();

    // If the end date is in the future, return CACHE_DISABLED.
    if ($end > time()) {
      return Cache::CACHE_DISABLED;
    }
   
    $values = ['start' => $start, 'end' => $end];

    return hash('sha256', serialize($values));
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
services:
  visitors.cache_context.date_range:
    class: Drupal\visitors\Cache\DateRangeCacheContext
    arguments: ['@visitors.date_range']
    tags:
      - { name: cache.context, context_id: visitors_date_range }

In the Views Filter plugin

public function getCacheContexts() {
  return Cache::mergeContexts(parent::getCacheContexts(), ['visitors_date_range']);
}

Remaining tasks

User interface changes

API changes

Data model changes

πŸ“Œ Task
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States bluegeek9

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024