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