SiteAlertController.php in Site Alert 8
File
src/Controller/SiteAlertController.php
View source
<?php
namespace Drupal\site_alert\Controller;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Render\RendererInterface;
use Drupal\site_alert\GetAlertsInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class SiteAlertController extends ControllerBase {
protected $entityTypeManager;
protected $renderer;
protected $getAlerts;
public function __construct(EntityTypeManagerInterface $entityTypeManager, RendererInterface $renderer, GetAlertsInterface $getAlerts) {
$this->entityTypeManager = $entityTypeManager;
$this->renderer = $renderer;
$this->getAlerts = $getAlerts;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('renderer'), $container
->get('site_alert.get_alerts'));
}
public function getUpdatedAlerts() {
$cache_metadata = new CacheableMetadata();
$cache_metadata
->addCacheTags($this->entityTypeManager
->getDefinition('site_alert')
->getListCacheTags());
$cache_metadata
->addCacheTags([
'rendered',
]);
$cache_metadata
->setCacheMaxAge($this->entityTypeManager
->getStorage('site_alert')
->getCacheMaxAge());
$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;
}
}