You are here

public function SiteAlertController::getUpdatedAlerts in Site Alert 8

1 string reference to 'SiteAlertController::getUpdatedAlerts'
site_alert.routing.yml in ./site_alert.routing.yml
site_alert.routing.yml

File

src/Controller/SiteAlertController.php, line 69

Class

SiteAlertController
Implements SiteAlertController class.

Namespace

Drupal\site_alert\Controller

Code

public function getUpdatedAlerts() {
  $cache_metadata = new CacheableMetadata();

  // Add the list cache tags so that the response will be invalidated when
  // the alerts change.
  $cache_metadata
    ->addCacheTags($this->entityTypeManager
    ->getDefinition('site_alert')
    ->getListCacheTags());

  // Add the 'rendered' cache tag as this response is not processed by
  // \Drupal\Core\Render\MainContent\HtmlRenderer::renderResponse().
  $cache_metadata
    ->addCacheTags([
    'rendered',
  ]);

  // Set the max age to the first scheduled change in visible alerts.
  $cache_metadata
    ->setCacheMaxAge($this->entityTypeManager
    ->getStorage('site_alert')
    ->getCacheMaxAge());

  // Apply the cache context that varies by the currently active alerts.
  $cache_metadata
    ->setCacheContexts([
    'active_site_alerts',
  ]);
  $build = [];
  foreach ($this->getAlerts
    ->getActiveAlerts() as $alert) {
    $build[] = [
      '#theme' => 'site_alert',
      '#alert' => [
        'severity' => $alert
          ->getSeverity(),
        'label' => $alert
          ->getLabel(),
        'message' => [
          '#type' => 'markup',
          '#markup' => $alert
            ->getMessage(),
        ],
      ],
      '#attached' => [
        'library' => [
          'site_alert/drupal.site_alert',
        ],
      ],
    ];
    $cache_metadata
      ->addCacheableDependency($alert);
  }
  $cache_metadata
    ->applyTo($build);
  $response = new HtmlResponse();
  $response
    ->setContent($this->renderer
    ->renderRoot($build))
    ->addCacheableDependency($cache_metadata);
  return $response;
}