Lines: 100.00%
| Line | Hits | Source |
|---|---|---|
| 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) { | |
| 40 | 7 | $this->dateRange = $visitors_date_range; |
| 41 | 7 | $this->time = $time; |
| 42 | } | |
| 43 | ||
| 44 | /** | |
| 45 | * {@inheritdoc} | |
| 46 | */ | |
| 47 | public static function getLabel() { | |
| 48 | 1 | return t('Visitors Date Range Filter'); |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * {@inheritdoc} | |
| 53 | */ | |
| 54 | public function getContext() { | |
| 55 | 7 | $start = $this->dateRange->getStartTimestamp(); |
| 56 | 7 | $end = $this->dateRange->getEndTimestamp(); |
| 57 | 7 | $now = $this->time->getCurrentTime(); |
| 58 | ||
| 59 | 7 | if ($end > $now) { |
| 60 | 7 | $end = $now; |
| 61 | } | |
| 62 | ||
| 63 | 7 | return "$start:$end"; |
| 64 | } | |
| 65 | ||
| 66 | /** | |
| 67 | * {@inheritdoc} | |
| 68 | */ | |
| 69 | public function getCacheableMetadata() { | |
| 70 | 2 | $metadata = new CacheableMetadata(); |
| 71 | ||
| 72 | 2 | $end = $this->dateRange->getEndTimestamp(); |
| 73 | 2 | $now = $this->time->getCurrentTime(); |
| 74 | ||
| 75 | 2 | if ($end > $now) { |
| 76 | // Disable caching by setting max-age to 0. | |
| 77 | 1 | $metadata->setCacheMaxAge(0); |
| 78 | } | |
| 79 | ||
| 80 | 2 | return $metadata; |
| 81 | } | |
| 82 | ||
| 83 | } |