SitewideAlertsController.php in Sitewide Alert 8
File
src/Controller/SitewideAlertsController.php
View source
<?php
namespace Drupal\sitewide_alert\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\sitewide_alert\SitewideAlertManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Render\Renderer;
class SitewideAlertsController extends ControllerBase {
protected $renderer;
private $sitewideAlertManager;
public function __construct(Renderer $renderer, SitewideAlertManager $sitewideAlertManager) {
$this->renderer = $renderer;
$this->sitewideAlertManager = $sitewideAlertManager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('renderer'), $container
->get('sitewide_alert.sitewide_alert_manager'));
}
public function load() {
$response = new CacheableJsonResponse([]);
$sitewideAlertsJson = [
'sitewideAlerts' => [],
];
$sitewideAlerts = $this->sitewideAlertManager
->activeVisibleSitewideAlerts();
$viewBuilder = $this
->entityTypeManager()
->getViewBuilder('sitewide_alert');
foreach ($sitewideAlerts as $sitewideAlert) {
$message = $viewBuilder
->view($sitewideAlert);
$sitewideAlertsJson['sitewideAlerts'][] = [
'uuid' => $sitewideAlert
->uuid(),
'message' => $this->renderer
->renderPlain($message),
'dismissible' => $sitewideAlert
->isDismissible(),
'dismissalIgnoreBefore' => $sitewideAlert
->getDismissibleIgnoreBeforeTime(),
'styleClass' => $sitewideAlert
->getStyleClass(),
'showOnPages' => $sitewideAlert
->getPagesToShowOn(),
'negateShowOnPages' => $sitewideAlert
->shouldNegatePagesToShowOn(),
];
}
$cacheableMetadata = (new CacheableMetadata())
->setCacheMaxAge(30)
->addCacheContexts([
'languages',
])
->setCacheTags([
'sitewide_alert_list',
]);
$response
->addCacheableDependency($cacheableMetadata);
$response
->setData($sitewideAlertsJson);
if ($expireDate = $this->sitewideAlertManager
->nextScheduledChange()) {
$response
->setExpires($expireDate
->getPhpDateTime());
}
$response
->setMaxAge(15);
$response
->setSharedMaxAge(15);
return $response;
}
}