Coverage index

src/Cache/DateRangeCacheContext.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Cache;
6
7
use Drupal\Component\Datetime\TimeInterface;
8
use Drupal\Core\Cache\CacheableMetadata;
9
use Drupal\Core\Cache\Context\CacheContextInterface;
10
use Drupal\visitors\VisitorsDateRangeInterface;
11
12
/**
13
 * Defines a custom cache context for Views, depending on TempStore date range.
14
 */
15
class DateRangeCacheContext implements CacheContextInterface {
16
17
  /**
18
   * The date range service.
19
   *
20
   * @var \Drupal\visitors\VisitorsDateRangeInterface
21
   */
22
  protected $dateRange;
23
24
  /**
25
   * The time service.
26
   *
27
   * @var \Drupal\Component\Datetime\TimeInterface
28
   */
29
  protected $time;
30
31
  /**
32
   * Constructs a DateRangeCacheContext object.
33
   *
34
   * @param \Drupal\visitors\VisitorsDateRangeInterface $visitors_date_range
35
   *   The date range service.
36
   * @param \Drupal\Component\Datetime\TimeInterface $time
37
   *   The time.
38
   */
39
  public function __construct(VisitorsDateRangeInterface $visitors_date_range, TimeInterface $time) {
407
    $this->dateRange = $visitors_date_range;
417
    $this->time = $time;
42
  }
43
44
  /**
45
   * {@inheritdoc}
46
   */
47
  public static function getLabel() {
481
    return t('Visitors Date Range Filter');
49
  }
50
51
  /**
52
   * {@inheritdoc}
53
   */
54
  public function getContext() {
557
    $start = $this->dateRange->getStartTimestamp();
567
    $end = $this->dateRange->getEndTimestamp();
577
    $now = $this->time->getCurrentTime();
58
597
    if ($end > $now) {
607
      $end = $now;
61
    }
62
637
    return "$start:$end";
64
  }
65
66
  /**
67
   * {@inheritdoc}
68
   */
69
  public function getCacheableMetadata() {
702
    $metadata = new CacheableMetadata();
71
722
    $end = $this->dateRange->getEndTimestamp();
732
    $now = $this->time->getCurrentTime();
74
752
    if ($end > $now) {
76
      // Disable caching by setting max-age to 0.
771
      $metadata->setCacheMaxAge(0);
78
    }
79
802
    return $metadata;
81
  }
82
83
}