You are here

protected function WebformEntityReferenceFormatterBase::setCacheContext in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Plugin/Field/FieldFormatter/WebformEntityReferenceFormatterBase.php \Drupal\webform\Plugin\Field\FieldFormatter\WebformEntityReferenceFormatterBase::setCacheContext()

Set cache context.

Parameters

array $elements: The elements that need cache context.

\Drupal\webform\WebformInterface|null $webform: The webform entity reference webform.

\Drupal\webform\Plugin\Field\FieldType\WebformEntityReferenceItem $item: The webform entity reference item.

3 calls to WebformEntityReferenceFormatterBase::setCacheContext()
WebformEntityReferenceEntityFormatter::viewElements in src/Plugin/Field/FieldFormatter/WebformEntityReferenceEntityFormatter.php
Builds a renderable array for a field value.
WebformEntityReferenceLinkFormatter::viewElements in src/Plugin/Field/FieldFormatter/WebformEntityReferenceLinkFormatter.php
Builds a renderable array for a field value.
WebformEntityReferenceUrlFormatter::viewElements in src/Plugin/Field/FieldFormatter/WebformEntityReferenceUrlFormatter.php
Builds a renderable array for a field value.

File

src/Plugin/Field/FieldFormatter/WebformEntityReferenceFormatterBase.php, line 98

Class

WebformEntityReferenceFormatterBase
Base class for 'Webform Entity Reference formatter' plugin implementations.

Namespace

Drupal\webform\Plugin\Field\FieldFormatter

Code

protected function setCacheContext(array &$elements, WebformInterface $webform, WebformEntityReferenceItem $item) {

  // Track if webform.settings is updated.
  $config = $this->configFactory
    ->get('webform.settings');
  $this->renderer
    ->addCacheableDependency($elements, $config);

  // Track if the webform is updated.
  $this->renderer
    ->addCacheableDependency($elements, $webform);

  // Calculate the max-age based on the open/close data/time for the item
  // and webform.
  $max_age = 0;
  $states = [
    'open',
    'close',
  ];
  foreach ($states as $state) {
    if ($item->status === WebformInterface::STATUS_SCHEDULED) {
      $item_state = $item->{$state};
      if ($item_state && strtotime($item_state) > $this->time
        ->getRequestTime()) {
        $item_seconds = strtotime($item_state) - $this->time
          ->getRequestTime();
        if (!$max_age && $item_seconds > $max_age) {
          $max_age = $item_seconds;
        }
      }
    }
    if ($webform
      ->status() === WebformInterface::STATUS_SCHEDULED) {
      $webform_state = $webform
        ->get($state);
      if ($webform_state && strtotime($webform_state) > $this->time
        ->getRequestTime()) {
        $webform_seconds = strtotime($webform_state) - $this->time
          ->getRequestTime();
        if (!$max_age && $webform_seconds > $max_age) {
          $max_age = $webform_seconds;
        }
      }
    }
  }
  if ($max_age) {
    $elements['#cache']['max-age'] = $max_age;
  }
}